Object-Oriented Programming – Is ‘Protected’ Reasonable Outside Virtual Methods?

encapsulationobject-oriented

so, suppose you have some fields and methods marked protected (non-virtual). presumably, you did this because you didn't mark them public because you don't want some nincompoop to accidentally call them in the wrong order or pass in invalid parameters, or you don't want people to rely on behaviour that you're going to change later.

so, why is it okay for that nincompoop to use those fields and methods from a subclass? as far as i can tell, they can still screw up in the same ways, and the same compatibility issues still exist if you change the implementation.

the cases for protected i can think of are:
non-virtual destructors, so you can't break things by deleting the base class.
virtual methods, so you can override 'private' methods called by the base class.
constructors in c++. in java/c# marking the class as abstract will do basically the same.

any other use cases?

Best Answer

Yes.

A situation where a non-virtual protected method makes sense might be something like bool IsInitialized(). The class is designed to be sub-classed. The sub-class might provide new methods, or overriding methods. In either case, before these methods can be run, it is important to check that the class is initialized. So the IsInitialized() method is provided for that purpose. It is intended to be used by the new or overriding methods in the sub-class only, and not the calling code. It is also intended that IsInitialized() not be overridden. The way to provide this is by declaring IsInitialized() to be protected and non-virtual.