How C++ virtual inheritance is implemented in compilers?

前端 未结 5 408
自闭症患者
自闭症患者 2020-12-24 13:49

How the compilers implement the virtual inheritance?

In the following code:

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

class B : public virtual A {
  publ         


        
5条回答
  •  有刺的猬
    2020-12-24 14:25

    The compiler does not create another constructor of B - but it ignores the A(1). Since A is virtually inherited, it is constructed first, with its default constructor. And since it's already constructed when B() is invoked, the A(1) part is ignored.

    Edit - I missed the A(3) part in C's constructor initialization list. When virtual inheritance is used, only the most derived class initializes the virtual base classes. So A will be constructed with A(3) and not its default constructor. The rest still stands - any initializations of A by an intermediate class (here B) are ignored.

    Edit 2, trying to answer the actual question regarding the implementation of the above:

    In Visual Studio (at least 2010), a flag is used instead of having two implementations of B(). Since B virtually inherits from A, before it calls A's constructor, the flag is checked. If the flag is not set, the call to A() is skipped. Then, in every class deriving from B, the flag is reset after it initializes A. The same mechanism is used to prevent C from initializing A if it's part of some D (if D inherits from C, D will initialize A).

提交回复
热议问题