Why must virtual base classes be constructed by the most derived class?

前端 未结 3 757
甜味超标
甜味超标 2020-12-01 20:43

The following code won\'t compile:

class A {
public:
    A(int) {}
};

class B: virtual public A {
public:
    B(): A(0) {}
};

// most derived class
class C         


        
3条回答
  •  醉话见心
    2020-12-01 21:33

    Because in the class hierarchy having a virtually inherited base class, the base class would/may be shared by multiple classes (in diamond inheritance for example, where the same base class is inherited by multiple classes). It means, there would be only one copy of the virtually-inherited base class. It essentially means, the base class must be constructed first. It eventually means the derived class must instantiate the given base class.

    For example:

    class A;
    class B1 : virtual A;
    class B2 : virtual A;
    class C: B1,B2 // A is shared, and would have one copy only.
    

提交回复
热议问题