7 January 2012

Constructors and Destructors


Virtual Destructors

It is legal and common to pass a pointer to a derived object when a pointer to a base
object is expected. What happens when that pointer to a derived subject is deleted? If
the destructor is virtual, as it should be, the right thing happens—the derived class’s
destructor is called. Because the derived class’s destructor will automatically invoke
the base class’s destructor, the entire object will be properly destroyed.

The rule of thumb is this: If any of the functions in your class are virtual, the destruc-
tor should also be virtual.


Virtual Copy Constructors

As previously stated, no constructor can be virtual. Nonetheless, there are times
when your program desperately needs to be able to pass in a pointer to a base object
and have a copy of the correct derived object that is created. A common solution to
this problem is to create a clone member function in the base class and to make it
virtual. A clone function creates a new copy of the current object and returns that
object.

Because each derived class overrides the clone function, a copy of the derived class is
created. 

0 comments:

Post a Comment