Virtual Inheritance: Is Base Ctor not called in most derived classes?

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 is Z():X(10){} Base(int k):a(k)not called, but when I change to Z():Base(10){}, it is called Base(int k):a(k). Why?

Thank.

+3
source share
3 answers

Since you used the keyword virtual, this is exactly what it does.

You must explicitly initialize Basein the initializer list Zto eliminate the ambiguity between initialization in Xand initialization in Y.

+7
source

. . , .

+3

. Z X Y, , virtual , a.

0

Source: https://habr.com/ru/post/1736299/


All Articles