Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When utilizing a class, there really is no difference between protected and private members. Neither are accessible to anything that utilizes the class. </p> <pre><code>class A { private: int privateNum; protected: int protectedNum; public: int publicNum; void SetNumbers(int num) { privateNum = num; //valid, private member can be accessed in member function protectedNum = num; //valid, protected member can be accessed in member function } }; void main() { A classA; classA.privateNum = 1; //compile error can't access private member classA.protectedNum = 1; //compile error can't access protected member classA.publicNum = 1; //this is OK classA.SetNumbers(1); //this sets the members not accessible directly } </code></pre> <p>The difference comes into effect when you inherit from a class with protected members. </p> <pre><code>class B : public A { }; </code></pre> <p>All private members of a base class are still private, and will not be accessible to the derived class. The protected members, on the other hand, are accessible to the inherited class, but are still not accessible outside of the inherited class.</p> <pre><code>class B : public A { public: void SetBNumbers(int num) { privateNum = num; //compile error, privateNum can only be accessed by members of A, not B protectedNum = num; //this works, as protected members can be accessed by A and B } }; void main() { B classB; classB.publicNum = 1; //valid, inherited public is still public classB.protectedNum = 1; //compile error, can't access protected member classB.privateNum = 1; //compile error, B doesn't know that privateNum exists classB.SetBNumbers(1); //this sets the members not accessible directly } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload