[prog] C++ inheritance - destructors

Kathryn Hogg kjh at flyballdogs.com
Tue May 27 10:38:59 EST 2003


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



-- 
Kathryn


More information about the Programming mailing list