[Solved] access protected variable in derived class c++


You don’t have a clear concept in object oriented programming. When you create two objects, then they are completely different from each other. They do not interact with each other until they are forced.So,

  • myMum and myDaughter are seperate objects and they do not share the values of their variables.
  • The last two outputs are basically garbage values. You have not initialized myDaughter’s familystuff

So, if you want to access protected members from derived class, you need to write the following :

int main()
{
    Daughter myDaughter(5,3,1);
    myDaughter.Show();
    cout << "FOO " << myDaughter.foo() << endl;
 }

Change the Daughter’s constructor to the following :

Daughter(int x,int y,int z)
    {
            SetStuff(x,y,z);
            a = familystuff + 1;
    }

You will get the desired output!!

solved access protected variable in derived class c++