[prog] C++ inheritance - destructors

Sue Stones suzo at bigpond.net.au
Wed May 28 19:25:39 EST 2003


On Wed, 28 May 2003 01:38, Kathryn Hogg wrote:
> Sue Stones said:
> >I have got the idea that Constructors arn't inherited, so if I am creating
> > a
> > derived class the constructor of the derived class has to call the
> > constructor of the base class.
>
> If a derived class doesn't explicitly call a constructor for a base class,
> the default constructor for the parent class.  In fact, the constructors
> for the parent classes will be called from the ground up.   For example,
> if you have a base class Vehicle and Car inherits from it, during the
> construction of a Car, it becomes a Vehicle and then becomes a Car.
>
> > But what happens with destructors?  If I need to call the destructor of a
> > base classhow do I do it?
>
> Destructors for a base class are called automatically in the reverse order
> of constructors.
>
> One thing to think about is with inheritence you may want to make the
> destructors virtual:
>
> class Vehicle {
> public:
>    ~Vehicle();
> };
>
> This is important if you ever need to delete a derived class when all you
> have is a pointer to the base class.  Say you have a "Vehicle *v" and you
> need to delete it.  So you call:
>
>     delete v;
>
> If Vehicle's destructor is non-virtual and this happens to actuall by a
> "Car *", the destructor will not call Car::~Car() - just
> Vehicle::~Vehicle()

If it is virtual can it be used to delete things that have been createdby the 
base class.

Vehicle::~Vehicle()
{
	delete [] rego;
}


In other words can a virtual function have code in it or is it just a kind of 
place-holder for a funtion to be defined by the derived classes?

sue











More information about the Programming mailing list