C++ Protected Methods – Real-World Scenarios

access-modifierscinheritanceobject-oriented

Today I noticed that I basically never use protected methods in C++ code, because I rarely feel the need to call non-public methods of a parent. I do use protected in Java in the template method pattern, but since you can override private methods in C++, I don't need protected there, either.

So what are some real-world scenarios where I would want to use protected methods in C++ code?

(Note that I'm not too fond of implementation inheritance in general, that might explain a lot…)

Best Answer

Here is an example

class Base {
public:
  // other members ...

protected:
  ~Base() { }
};

Used as a non-polymorphic base class. But users will not be allowed to call delete baseptr; on it because the destructor is inaccessible. Since it has no virtual destructor, allowing people to do that would be undefined behavior. See "Virtuality" by Herb.