C++ : Order of finalization of a derived class object

238 Views Asked by At

I know the order of finalization of a class object is the following :

  • Execute body of destructor
  • Destroy the object (i.e. deallocate memory used for data members)

Now I was asked about the order of finalization for derived class objects. I suppose it is exactly the same, but is the destructor of the base class object also called after doing the above steps?

I don't think so but wanted to be sure for the exam.

Thanks for your help :)

1

There are 1 best solutions below

0
On BEST ANSWER

Destructors are called in the reverse order of construction. It means that the destructor of the base class will be automatically called after the destructor of the derived class.

Take this example:

class Foo
{
protected:
    SomeType var;

public:
    ~Foo() {}
};

class Baz : public Foo
{
public:
    ~Baz()
    {
        var.doSomething();
    }
};

If the destructor of the base class Foo was called before the destructor of class Baz, then the object var would have been destroyed (its destructor would have been automatically called at Foo's destruction) and you would enter the realm of undefined behavior.

This is a simple and intuitive explanation of why the destructors are called this way.