Software & Finance





C++ FAQ - How do I use Virtual Destructor?





We can have virtual destructor. It is very useful when you need to delete the object using base class pointers, especially when you implement polymorphism.


Source Code


class Shape

{

public:

    Shape()

    {

        std::cout << "Calling Shape Constructor\n";

    }

    virtual ~Shape()  // Pure Virtual Destructor

    {

        std::cout << "Calling Shape Destructor\n\n";

    }

    virtual void draw() = 0;  // Pure Virtual Function

    virtual void display() { };

};

 

class Rect1 : public Shape

{

    int l,b;

public:

    virtual ~Rect1()

    {

        std::cout << "Calling Rectangle Destructor\n";

    }

    Rect1()

    {

        std::cout << "Calling Rectangle Constructor\n\n";

    }

    virtual void draw() {}

    virtual void display() { };

};

 

class Circle : public Shape

{

    int r;

public:

    virtual ~Circle()

    {

        std::cout << "Calling Circle Destructor\n";

    }

    Circle()

    {

        std::cout << "Calling Circle Constructor\n\n";

    }

    virtual void draw() {};

    virtual void display() { };

};

 

class Triangle : public Shape

{

    int a,b,c;

public:

    virtual ~Triangle()

    {

        std::cout << "Calling Triangle Destructor\n";

    };

    Triangle()

    {

        std::cout << "Calling Triangle Constructor\n\n";

    }

    virtual void draw() {};

    virtual void display() { };

};

 

 

int _tmain(int argc, _TCHAR* argv[])

{

 

    Shape *p[]  = {

              new Rect1(),

              new Circle(),

              new Triangle(),

    };

 

    for(int i = 0; i < sizeof(p) / sizeof(p[0]); i++)

        delete p[i];

 

    return 0;

}


Output


Calling Shape Constructor

Calling Rectangle Constructor

 

Calling Shape Constructor

Calling Circle Constructor

 

Calling Shape Constructor

Calling Triangle Constructor

 

Calling Rectangle Destructor

Calling Shape Destructor

 

Calling Circle Destructor

Calling Shape Destructor

 

Calling Triangle Destructor

Calling Shape Destructor