0

The output of the program below is: 5 5

#include <iostream>
using namespace std;

struct A
{
public:
    int myInt;
    A(int n): myInt(n){}
    A(): myInt(5) {}
};


class B : virtual public A
{
public:
    B(int n):A(10) {}
    B():A(10) {}
};

class C : virtual public A
{
public:
    C(int n):A(3*n) {}
};

class D : public B, public C
{
public:
    D(int n=90) : C(2*n), B(n) {}
};

class E : public D
{
public:
    E(int n=20):D(n-1) {}
};

int main()
{
    D d(100);
    cout << d.myInt << endl;
    E e;
    cout << e.myInt << endl;
    return 0;
}

Consider the object d. From what I understand the inheritance is constructed based on the order of the inheritance list (rather than the initialization list) so B class is constructed first with the param 100 which goes to class A with the parameter 10. So now A sets myInt to the value 10. The same goes for Class c and because myInt is virtual then it is set to the number 600. I never expected 5. why is this happening?

Tom
  • 9,275
  • 25
  • 89
  • 147

1 Answers1

0

See article in parashift:

Because a virtual base class subobject occurs only once in an instance, there are special rules to make sure the virtual base class's constructor and destructor get called exactly once per instance. The C++ rules say that virtual base classes are constructed before all non-virtual base classes. The thing you as a programmer need to know is this: constructors for virtual base classes anywhere in your class's inheritance hierarchy are called by the "most derived" class's constructor.

eladidan
  • 2,634
  • 2
  • 26
  • 39