Are multiple-inherited constructors called multiple times?

前端 未结 3 698
盖世英雄少女心
盖世英雄少女心 2020-12-16 12:07

Are multiple-inherited constructors called multiple times? And in what order are constructors called? Does this depend on the order in the inheritance list?

Here is

3条回答
  •  旧巷少年郎
    2020-12-16 13:11

    This is answered in: http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.14

    The very first constructors to be executed are the virtual base classes anywhere in the hierarchy. They are executed in the order they appear in a depth-first left-to-right traversal of the graph of base classes, where left to right refer to the order of appearance of base class names.

    Since your multiple inheritance declaration lists DerivedBaseTwo first, its construction order will be executed before DerivedBaseOne's.

    So in your Derived class, DerivedBaseTwo and its chain is created first, that is:

    1 - Base then DerivedBaseTwo

    And then DerivedBaseOne and its chain:

    2 - Base then DerivedBaseOne

    And then:

    3 - Derived is created after everything else.

    Also, with multiple inheritance be mindful of the Diamond Inheritance Problem

提交回复
热议问题