views:

83

answers:

3
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.

+3  A: 

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

Space_C0wb0y
+6  A: 

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.

Joe Gauterin
@Joe, Clean Answer :). Thanks a Lot
mahesh
A: 

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.

jasonline