Where is the “virtual” keyword necessary in a complex multiple inheritance hierarchy?

后端 未结 7 1814
死守一世寂寞
死守一世寂寞 2021-01-30 19:00

I understand the basics of C++ virtual inheritance. However, I\'m confused about where exactly I need to use the virtual keyword with a complex class hierarchy. F

7条回答
  •  别跟我提以往
    2021-01-30 19:21

    Edited: I thought A was the most derived class ;)

    @Luther's answer really cool, but back to the original question:

    You NEED to use virtual inheritance when inheriting from any class from which at least one other class inherits in the inheritance hierarchy (in Luther's diagrams it means at least two arrows point to the class).

    Here it's unnecessary before D, F, G and H because only one class derives from them (and none derives from I at the moment).

    However, if you don't know beforehand whether or not another class will inherit from your base class, you can add in virtual as a precaution. For example it's recommended for an Exception class to inherit virtually from std::exception by no other than Stroustrup himself.

    As Luther has noted, it modifies the instantiation order (and has a slight effect on performances) but I would consider any design relying on the construction order to be wrong to begin with. And just as a precision: you still have the guarantees that base classes are initialized before any attribute of the derived class, and therefore before the execution of the derived's constructor body.

提交回复
热议问题