0

I have a child constructor like this:

Child():Parent(){

}

So the destructor of the child is:

~Child(){

}

And the parent has something like:

Parent(){
  abc.Construct();
} 

~Parent(){
  abc.Destruct();
}

How do I make sure all the allocations made during initialization (in the Parent() constructor) are deleted during destruction of the child?

ssn
  • 2,631
  • 4
  • 24
  • 28

3 Answers3

1

What's done in the Parent constructor should be undone in the Parent destructor, not in the Child destructor.

The Parent destructor is automatically called during destruction of the Child; just like the Parent constructor is automatically called during construction of the child.

The Child can specify explicitly how to initialize the Parent by means of a constructor's initialization list. This is needed because the Parent class does not need to have a default constructor. It is not required to specify explicitly how to destroy the Parent during destruction of the Child, because every class has only a single destructor and that destructor does not require any arguments.

Oswald
  • 31,254
  • 3
  • 43
  • 68
0

When an object gets destroyed, the destructors of all full constructed [sub-]objects get called (the issue about full construction is important when throwing an exception during construction; once construction completed, all subjects and the object itself will be destroyed). That is, each class just looks after its own resources and leaves destruction of its subobjects to their respective destructors.

In addition being very precise about which destructors are called, the language is also very precise about the order: destructors are called in exactly the reverse order the constructors are called. That is, the Parent class destructor is called after the Child class destructor and all of the destructors of Child's members are completed.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

The bigger concern is what happens if you delete a pointer to the base class? I hope that your destructor is declared as virtual in the base class.

shawn1874
  • 1,288
  • 1
  • 10
  • 26