Search code examples
c++classprivatememberprotected

Private and Protected Members


I'm having trouble understanding the difference between private and protected members in a C++ class. In simple terms, what is the difference?


Solution

  • protected members are accessible by derived classes. private members are not.

    Generally (most of the time) members should either be private or public. It is rare and unusual to need a protected member (edit) in a well-designed system.

    EDIT:

    Maybe I should elaborate on why protected members can be a code-smell.

    If derived classes have access to data members that other classes do not, this could be an indication that the base & derived classes are too tightly coupled. The derived classes have access to the base class' state, and therefore the base class' state is subject to corruption. If this were not the case, then there's also often no reason to just make the data members public.

    Others have gone in to greater detail on this.

    Here is what Stroustrup says in his text:

    Members declared protected are far more open to abuse than members declared private . In particular, declaring data members protected is usually a design error. Placing significant amounts of data in a common class for all derived classes to use leaves that data open to corruption. Worse, protected data, like public data, cannot easily be restructured because there is no good way of finding every use. Thus, protected data becomes a software maintenance problem.

    See also this question.