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?
Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++
class
ses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.A protected nonstatic base class member can be accessed by members and friends of any classes derived from that base class by using one of the following:
private = accessible by the mothership (base class) only (ie only my parent can go into my parent's bedroom)
protected = accessible by mothership (base class), and her daughters (ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)
public = accessible by mothership (base class), daughter, and everyone else (ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)
Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .
Attributes and methods marked as
protected
are -- unlike private ones -- still visible in subclasses.Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them
private
.Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.
Of course friend functions throw this out the window, but oh well.