Construction and destruction inheritance in C++

Even though the concept of construction and destruction may seem a simple subject, many people still get confused about the way it works.

Let's create two structures such as Parent and Child.

Parent will be the base structure and Child will inherit from it.

The above code will output the following results :

1 3 4 2

The common mistake that result from this code is that one might think that only 3 4 will be outputted. But since Child inherit from Parent, Child is now tight to Parent and cannot exist without it.

In order to create Child, the program must create Parent first. Which is why the creation order will be Parent --> Child

As for the destruction is the other way around. We can't destroy Parent and then Child, it's like removing the foundation of a building while keeping the roof. Which is why the destruction order will be Child --> Parent

What about using pointers

Introducing pointers to our code will make it trickier and that's the fun part.

Let's take the same example as before and use pointer to instantiate our structure

The above code will output the following results :

1 3 2

But wait ? there's a number missing, why the Child is never destroyed.”

A is a Parent pointer, upon executing the program, the creation will follow the pattern we know which is Parent --> Child, and when destroying, we would have expected the same pattern we've seen which is Child --> Parent.

Even though Child is an extended class of Parent, the function call is solved at compile time, meaning that the pointer, will call only the function of the object it points to which is the one of the Parent.

To solve that issue, we need to make use of virtual functions, and update our code as follow

Virtual functions are solved at run-time, which will ensure that the correct function is called for an object, regardless of the type of reference or pointer used for function call.

So now when executing our code, we will get the following outputs

1 3 4 2

Technical explanation

To get more technical, virtual functions introduces the concept of VTABLE(Virtual Table) and VPTR (Virtual pointer).

When we create a pointer of type Parent and initialize it with the address of the Child object. Upon Child creation, the compiler will add a VPTR as a class member to Child that will point to the VTABLE which is an array of function pointers who point to the right function call when executing the code. Such as

Consider Foo() as virtual function declared only on struct Parent. Thus when executing Foo() function from a Child pointer, it will point to the Parent Foo() function since Child doesn't override it.