Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance hierarchy: Constructor & Destructor execution sequence

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?

like image 468
Azodious Avatar asked Aug 16 '11 12:08

Azodious


People also ask

How are constructors called in inheritance hierarchy?

For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.

Can we use constructor in inheritance?

No, constructors cannot be inherited in Java. In inheritance sub class inherits the members of a super class except constructors. In other words, constructors cannot be inherited in Java therefore, there is no need to write final before constructors.

What happens to constructor in inheritance?

In the inheritance, the constructors never get inherited to any child class. In java, the default constructor of a parent class called automatically by the constructor of its child class.

What is the order of constructor execution in the case of inheritance?

In case of inheritance if we create an object of child class then the parent class constructor will be called before child class constructor. i.e. The constructor calling order will be top to bottom. So as we can see in the output, the constructor of Animal class(Base class) is called before Dog class(Child).


1 Answers

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.

like image 152
eran Avatar answered Oct 23 '22 05:10

eran