private versus protected

When I first started out in C++, I read a book written over five years ago whose author recommended making a habit out of using "protected" instead of "private." He explained that there will be so many times when a programmer would derive a class or struct and forget that the member variables and/or functions in the parent are private.

But I rarely see protected being used. Why is that? Is making things private better than protected?
Yes as a rule of thumb always make data members private. Creating protected members just destroys the data abstraction associated with inheritance and black box methods for clients. Making members protected makes it easier for clients to couple themselves to your data. Always private, it is not that hard to make accessors and mutators
> But I rarely see protected being used. Why is that?

One, the protected access specifier is meaningful only in classes that have been specifically designed for inheritance; a somewhat small subset of all the classes in a program.

Two, even in a class designed for inheritance, protected is useful only in a specific situation - when we want to provide a hook by which derived class authors can apply customizations.

Classic examples of meaningful uses of the protected access specifiers are the factory method and template method patterns. For examples from the standard library, look at the protected member functions in classes specifically designed for inheritance. For example:
std::basic_streambuf<> http://en.cppreference.com/w/cpp/io/basic_streambuf


Topic archived. No new replies allowed.