Home > programming > Virtual Destructors

Virtual Destructors


Instructions

1
Determine when to use a virtual destructor. A destructor for a class should be virtual when an object of a derived class will be destroyed by invoking the base class destructor. The destructor must be virtual when you delete a pointer to an object and it is possible that it points to a derived class.

2
Learn an important difference between a destructor and other member methods. In both cases, the method of the derived class is invoked if it is implemented. However, the base class destructor is subsequently called whereas this does not happen with other methods.

3
Consider the following example of a virtual destructor:

#include 
class Base_class
{
public:
Base_class(){ cout<<"Constructor: Base_class"<
// virtual keyword is needed here
virtual ~ Base_class(){ cout<<"Destructor : Base_class"<
};
class Derived_class: public Base_class
{ public:
Derived_class(){ cout<<"Constructor: Derived_class"<
~ Derived_class(){ cout<<"Destructor : Derived_class"<
};
void main()
{
Base_class *p = new Derived_class();
delete p;
}

4
Observe the use of the virtual keyword in the example in Step 3. If the destructor of the base class were not declared as virtual, the destructor of the derived class would not get called.

5
Implement at least an empty body for a virtual destructor since a pure virtual function cannot be declared.

Read more: How to Use C++ Virtual Destructors | eHow.com http://www.ehow.com/how_2156256_use-c-virtual-destructors.html#ixzz1HO7EBfW7

Advertisements
Categories: programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: