+ 1

Doesn't the public access specifier already allow derived classes?

I don't see the point of the protect access specifiers when public does the same thing.

17th Mar 2020, 12:38 PM
Donovan Thompson
Donovan Thompson - avatar
3 Answers
+ 4
public access specifiers allows access to the members not only from derived classes but also from outside of the class. protected access specifers allows access from only the same and derived classes. You can't access to protected members outside of a class. for example, it is not good if a user of your class will change some internal state of the object, so declare setStatus as protected: class A{ protected: void setStatus(int status); // accessible, ok derived class can change it public: int getStatus(); }; class B: public A{ public: B(){ setStatus(Initialized); } }; //.... somewhere in code: B b; b.setStatus(SignedIn); //will not compile as setStatus is protected auto ststus2 = b.getStatus(); //will compile
17th Mar 2020, 1:58 PM
andriy kan
andriy kan - avatar
+ 1
You cannot access protected member out of the class while you can do it with public member.
17th Mar 2020, 1:56 PM
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ - avatar