Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing a member variable's address in derived class.Behavior change when member is having different access specifier
    primarykey
    data
    text
    <p>I have a base class A and derived class B</p> <p>class B is derived from A as public </p> <p>I want to access the member variable's address if <strong>A is class a is member variable</strong> </p> <p>I am observing different behavior when i am using protected and public access specifier.</p> <p>When member a of class A is <strong>protected</strong> in this case i am getting:</p> <p><code>cout&lt;&lt;&amp;A::a &lt;&lt; endl;</code> throwing me an compiler error..</p> <p>but <code>cout&lt;&lt;&amp;(A::a)&lt;&lt;endl;</code> is valid and giving me proper result.</p> <p>and When member a of class A is <strong>public</strong> in this case i am getting: </p> <p>Why this behavior?</p> <p>Here is the full code :</p> <pre><code>#include &lt;iostream&gt; using namespace std; class A { protected: int a; void fun() { cout&lt;&lt;"A's fun"&lt;&lt;endl; } public: A(int Aarg):a(Aarg) { cout &lt;&lt; "A's construction done" &lt;&lt;endl; } }; class B: public A { protected: int b; public: void fun() { cout &lt;&lt; "B's fun"&lt;&lt;endl; } B(int As, int Bs):A(As), b(Bs) { std::cout&lt;&lt;"B's Construction Done" &lt;&lt;std::endl; } void show() { A::fun(); //cout &lt;&lt; a &lt;&lt; endl; cout&lt;&lt;&amp;A::a &lt;&lt; endl; //compilation error } }; int main() { B(10,20).show(); return 0; } </code></pre> <p><strong>Now there is a undefined behavior i am able to observe:</strong></p> <p>If i make my member variable a in class A as public then there will not be any compilation error but output is coming as 1 i dont know why..</p> <pre><code>class A{ public: int a .... .... </code></pre> <p>OUTPUT:</p> <p>A's construction done</p> <p>B's Construction Done</p> <p>A's fun</p> <p>0027F91C</p> <p>1 (why 1) and no errors as I was able to get when I tried to access protected member?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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