Priyanka Mishra
Priyanka Mishra

Reputation: 10728

Virtual Inheritance : Base Ctor not calling in Most Derived Class?

class Base
{
      public:
          Base(){}
          Base(int k):a(k) 
          {     
          }
            int a;
};

class X:virtual public Base
{
      public:
            X():Base(10){}
            int x;
};

class Y:virtual public Base
{
      public:
            Y():Base(10){}
            int y;
};

class Z:public X,public Y
{
public:
    Z():X(10){}
};

int main()
{
           Z a;
           cout << a.a;
           return 1;
}

In the above case, for Z():X(10){} Base(int k):a(k) is not calling, but when i change to Z():Base(10){} the Base(int k):a(k) is called. Why ?

Thank you.

Upvotes: 2

Views: 425

Answers (3)

jasonline
jasonline

Reputation: 9056

The initializer list in the most derived constructor is used to initialize your base classes. Since class Z inherits from class X and Y which inherits from a common base class, the virtual keyword is used to create only a single subobject for the base class in order to disambiguate when accessing the data member a.

Upvotes: 0

JoeG
JoeG

Reputation: 13192

Because you used the virtual keyword - that's exactly what it does.

You have to explicitly initialize Base in the initializer list of Z in order to disambiguate between the initialization in X and the initalization in Y.

Upvotes: 7

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76828

See this question. The gist is, that when using virtual inheritance you have to call the base class constructor explicitly.

Upvotes: 3

Related Questions