Why virtual base class constructors called first? [duplicate]

南笙酒味 提交于 2019-12-13 11:26:39

问题


Possible Duplicate:
In C++, what is a virtual base class?
virtual inheritance

why is it so that the constructors of virtual base classes are called from most derived class...and in the inheritance hierarchy first the objects to virtual base classes are created...whats the logic behind this?

I understand that using virtual inheritance as in diamond structure using virtual inheritance only one copy of the most base class is created but what exactly is virtual doing in a linear inheritance.

class A{};
class B : virtual public A {};  
class C : virtual public B {};

What actually we try to achieve on using this kind of inheritance?

Also what is the object layout in case of virtual inheritance ?

Can someone explain the logic behind this kind of behaviour in C++?


回答1:


Virtual inheritance should arguably be the default. If I write something like:

class Base
{
public:
    virtual ~Base() {}
    virtual void f() = 0;
    virtual int g() const = 0;
    //  ...
};

, it is clear that this class is meant to be inherited from. If I later write:

class Middle : public virtual Base
{
public:
    virtual void f();  
};

, the class is still clearly meant to be a base class—it has only implemented part of the interface. In this case, the inheritance should be virtual, since I don't know (or don't want to impose just one solution) whether the implementation of g() will be in a further derived class, or in a sister class (mixin-technology). Thus,

class Derived1 : public Middle
{
public:
    virtual int g() const;
};

No diamand, but the author of Middle didn't know that this would be the case, and didn't want to forbid:

class M2 : public virtual Base
{
public:
    virtual int g() const;
};

class Derived2 : public Middle, public M2
{
};

And given such a hierarchy, who should call Base's constructor. The only reasonable candidate is Derived2.



来源:https://stackoverflow.com/questions/10536091/why-virtual-base-class-constructors-called-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!