Monday, November 28, 2011

Inheritance and Order of Constructor Calls

For the code segment below, how many times of base class constructor will be called?

  1. For single inheritance, the order is always the same: base class constructor first, then its own constructor.
  2. For multiple inheritance, call the virtual base constructor first if any, then follow the order from left to right for non-virtual base constructors, and finally call its own constructor. Note that only a unique set of virtual base constructors will be called, which is exactly the purpose of virtual inheritance.

Example 1:
Output 1:
Base constructor
Foo1 constructor
Base constructor
Foo2 constructor
Multi constructor

Example 2:
Output 2:
Base constructor
Foo1 constructor
Base constructor
Foo2 constructor
Multi constructor

Example 3:
Output 3:
Base constructor
Base constructor
Foo1 constructor
Foo2 constructor
Multi constructor

Example 4:
Output 3:
Base constructor
Foo1 constructor
Foo2 constructor
Multi constructor

No comments:

Post a Comment