Private and Protected Members : C++


Question

Can someone enlighten me as to the difference between private and protected members in classes?

I understand from best practice conventions that variables and functions which are not called outside the class should be made private - but looking at my MFC project, MFC seems to favor protected.

What's the difference and which should I use?

1
256
11/6/2018 2:45:07 PM

Accepted Answer

Private members are only accessible within the class defining them.

Protected members are accessible in the class that defines them and in classes that inherit from that class.

Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.

Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ for a better understanding of the issue. This question about protected variables might also help.

345
8/30/2017 3:46:30 PM

Public members of a class A are accessible for all and everyone.

Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon