Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between private and protected members of C++ classes?

What is the difference between private and protected members in C++ 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?

like image 528
Konrad Avatar asked Oct 22 '08 09:10

Konrad


People also ask

What is the difference between protected and private class member?

Private members are accessible within the same class in which they are declared. Protected members are accessible within the same class and within the derived/sub/child class. Private members can also be accessed through the friend function. Protected members cannot be accessed through the friend function.

What's the difference between protected and private?

private: The type or member can be accessed only by code in the same class or struct . protected: The type or member can be accessed only by code in the same class , or in a class that is derived from that class .

What is the difference between private and protected inheritance?

protected inheritance makes the public and protected members of the base class protected in the derived class. private inheritance makes the public and protected members of the base class private in the derived class.


1 Answers

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.

like image 99
Firas Assaad Avatar answered Sep 21 '22 17:09

Firas Assaad