Home > Mobile >  c virtual inheritance doesn't work, how do I use the multiple parents' members?
c virtual inheritance doesn't work, how do I use the multiple parents' members?

Time:01-20

enter image description here

What did I do wrong?

CodePudding user response:

I was stupid. What virtual inheritance mean is to make the member become one. What I really want is just 2 copies of the members, just eliminate virtual.

class A {
protected:
    int a = 10;
public:
    A(int i):a(i){}
    virtual ~A(){}
};
class A1 : public /*virtual*/ A
{
public:
    A1(int i) :A(i) {};
};
class A2 : public /*virtual*/ A
{
public:
    A2(int i) :A(i) {};
};
class B : public A1, public A2
{
public:
    B(int a1, int a2): A1(a1), A2(a2) {}
    void test()
    {
        cout << A1::a << endl;
        cout << A2::a << endl;
    }
};
void test()
{
    B(1, 2).test();
    cout << sizeof(B);
}

CodePudding user response:

The result is correct, while the real reason is when you are using virtual inheritance, D ctor first uses AA's default ctor, n is not assigned. If you want to use AA(name, a), you need to explicitly use that in D.

  •  Tags:  
  • Related