Inheritance hierarchy: Constructor & Destructor execution sequence

大憨熊 提交于 2019-12-23 09:31:43

问题


Here http://www.parashift.com/c++-faq-lite/multiple-inheritance.html section [25.14] says

The very first constructors to be executed are the virtual base classes anywhere in the hierarchy.

I tried to verify it using following program:

           A (pure virtual)
           |
           B
           |
           C
(virtual)/   \ (virtual)
       E       D
         \   /
           F
           |
           G (pure virtual)
           |
           H

each class has a c'tor and virtual d'tor. the output is as follows:

A
B
C
E
D
F
G
H
~H
~G
~F
~D
~E
~C
~B
~A
Press any key to continue . . .

but as per quote virtual base classes constructors should be executed first.

what did I understand wrong?

EDIT: To clear my question, As per my understanding this behaviour has nothing to do with whether a base class is virtual or not. but quote insists on Virtual Base class. am I clear or something fishy there?


回答1:


Virtual base classes cannot be constructed if the classes they inherit from are not constructed first. So in your case, non-virtual base classes are constructed because the virtual ones depend on them: C can't be constructed until A and Bare. Therefore, A and B are indeed constructed before C, even though C is virtually inherited.



来源:https://stackoverflow.com/questions/7078417/inheritance-hierarchy-constructor-destructor-execution-sequence

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