0

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 :)

Kevin
  • 2,813
  • 3
  • 20
  • 30
  • 2
    _"After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X’s direct non-variant non-static data members, **the destructors for X’s direct base classes and, if X is the type of the most derived class (12.6.2), its destructor calls the destructors for X’s virtual base classes**"_. (from point 8 of the section on Destructors in the C++ ISO standard) – Michael Jan 05 '15 at 11:29
  • This question might help you, http://stackoverflow.com/questions/677620/do-i-need-to-explicitly-call-the-base-virtual-destructor – smali Jan 05 '15 at 11:32
  • We don't call it "finalization" in C++. Please adjust your terminology to make this question searchable. – Lightness Races in Orbit Jan 05 '15 at 12:35

1 Answers1

0

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.

Călin
  • 347
  • 2
  • 13