-5

I have a mother class and a derived daughter class. I am trying to access the protected variable 'familystuff' in the derived class. Both ways that I am trying to access it aren't working. When I compile and run it, I get the following output:

5 3 1

1

Familie 32768

FOO 32767

class Mother
 {
 private:
        int motherstuff;
 protected:
         int familystuff;
 public:
         int everyonesstuff;
         void SetStuff(int a, int b, int c){
            motherstuff = a;
            familystuff = b;
            everyonesstuff = c;
         }
         void Show(){
            cout << motherstuff << " " << familystuff << " " <<everyonesstuff << endl;
        }
};

class Daughter : public Mother
{
public:
    Daughter()
    {
            a = familystuff + 1;
    }
    void Show(){
            cout << "Familie " << a << endl;
    }
    int foo() { return familystuff;}
    private:
        int a;
 };

 int main(){

    Mother myMum;
    myMum.SetStuff(5,3,1);
    myMum.Show();
    cout << myMum.everyonesstuff << endl;

    Daughter myDaughter;
    myDaughter.Show();
    cout << "FOO " << myDaughter.foo() << endl;
}
Anja
  • 5
  • 4

2 Answers2

1

There are several things wrong here:

  1. myDaughter and myMum are different objects. You imply some kind of relationship between them, but there is none.

  2. Your code has undefined behaviour, because your Daughter constructor uses the uninitialised member variable familystuff in an addition operation.

  3. You should initialise your data members like this:

    Mother::Mother() : motherstuff(0), familystuff(0), everyonesstuff(0) {}

    Daughter::Daugher() : a(familystuff + 1) {}

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
1

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!!

Richa Tibrewal
  • 468
  • 7
  • 26