user7336243
user7336243

Reputation:

Inheritance shared memory

I have a question which I can't answer logically. Why is it after I run the following code:

class foo1
{
private:
    int age;
public:
    foo1(int _age) :age(_age) {}
    void print() { std::cout << age << std::endl; }
};

class foo2 :virtual public foo1
{
    int grade;
public:
    foo2(int _age, int _grade) :foo1(_age), grade(_grade) {}
};


class foo3 :virtual public foo2
{
private:
    int score;
public:
    foo3(int _age, int _grade, int _score) : 
          foo1(_age), foo2(5000, _grade), score(_score) {}
};

int main()
{
    foo3 k(77,2,3);
    k.print();
}

The console output is 77, rather than 5000. My reason for thinking that 5000 would be the right output ( but I am wrong ) is that when we I use the initializer list for the constructor of foo3 the following happens:

1) The constructor of foo1 sets the age to 77.

2) After that the constructor of foo2 sets the age to 5000 and the grade to 2, because foo2 uses the the constructor of foo1.

Why doesn't the constructor of foo2 change the value set by the constructor foo1

Upvotes: 3

Views: 128

Answers (1)

The Techel
The Techel

Reputation: 873

The constructor for a virtually inherited class is always called by the most derived class. In your case it's foo3 which does. The constructor call of foo1 in foo2 is skipped.

Upvotes: 4

Related Questions