开发者

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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜