What is the difference between private and protected access specifiers? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the difference between private and protected access specifiers?

What is the difference between private and protected access specifiers and how it work with derived class.

2nd Dec 2016, 8:41 AM
A Umesh
A Umesh - avatar
5 Answers
+ 3
class NewStruct { public : int publicMember; protected: int protectedMember; private: int privateMember; }; Anything can use publicMember, pretty simple. Now, everything in the system does not 'know' that NewStruct contains privateMember, only NewStruct knows it. Yes, ONLY, which means that even protectedMember and publicMember don't know it, which means nothing except for NewStruct can access to it. For protectedMember, everything outside of NewStruct cannot access to it. But everything inside of NewStruct can access to it. All of these can happen to inheritance too. Consider this : A class 'Test' inherits from NewStruct. If inheritance is protected, only Test, and whatever is inside of it, knows that that they are inherited from NewStruct , meaning that only things inside Test can access to the inherited class.
2nd Dec 2016, 9:09 AM
Wen Qin
Wen Qin - avatar
+ 3
I made an error in my previous answer, I edited it and added protected and inheritance inside it.
2nd Dec 2016, 9:09 AM
Wen Qin
Wen Qin - avatar
+ 2
if you use private access specifier then you can not access member into derived class but if you use protected then you can access private members of base class
2nd Dec 2016, 8:50 AM
khushal Patel
+ 1
Firstly, talking about the members of the class (variables and functions): -If a class member is defined as private, it can't be accessed by anything outside the class (not even by the objects of the same class). It can only be accessed by other member functions within the same class. Private members are not inherited. -If a member is defined as protected, it can be accessed through the derived class as well as through members of the same class. Protected members are inherited. Mode of Inheritance: Private- All inherited members become private in the derived class. Protected- All inherited members become protected in the derived class. Public- Protected members become protected, public members become public in derived class. Private members are not inherited.
2nd Dec 2016, 10:34 AM
Subhash Satish
0
Thanks k2 for your answer but I want to know the difference between private and protected. I have edited my question.
2nd Dec 2016, 8:50 AM
A Umesh
A Umesh - avatar