Calling a virtual base class's overloaded constructor

后端 未结 4 1085
孤城傲影
孤城傲影 2021-01-11 16:42

Is there a (practical) way to by-pass the normal (virtual) constructor calling order?

Example:

class A
{
    const int i;

public:
          


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 17:13

    Unfortunately, you will always have to call the virtual base classes constructor from the most derived class.

    This is because you are saying that the virtual base is shared between all classes that derive from it for the instance of the object. Since a constructor may only be called once for a given instaniation of an object, you have to explicitly call the constructor in the most derived class because the compiler doesn't know how many classes share the virtual base (paraphrased (probably poorly) from The C++ Programming Language 3rd edition, section 15.2.4.1). This is because the compiler will start from the most base class's constructor and work to the most derived class. Classes that inherit from a virtual base class directly, will not, by the standard, call their virtual base classes constructor, so it must be called explicitly.

提交回复
热议问题