on Leave a Comment

C++ Virtual Destructor

We know that destructor is automatically called before an object destroys. We can also define our destructor in class, otherwise default destructor is called. Destructor releases all resources allocated to an object. We can also make virtual destructor in class, which tells the compiler to perform late binding. Virtual destructor can be used when we want to perform late binding of destructor.

Syntax of Virtual Destructor in C++

Virtual keyword is used before virtual destructor declaration.

virtual ~ class_name()
{
  //Destructor body

When to use virtual destructor?

When we stores the address of derived class object in base class pointer, then compiler binds the base class destructor to base class pointer because compiler only sees the type of pointer rather than the content of pointer and this problem is caused by early binding. We can solve this problem by making base class destructor as virtual destructor.

Note: Derived class pointer automatically calls the base class pointer after performing its tasks.

Example of Non-Virtual Destructor:

#include<iostream>
using namespace std;
void test();
class A
{
private:
    int a;
public:
    ~ A()
    {
        cout<<"\nBase class destructor";
    }
};
class B: public A
{
private:
    int b;
public:
    ~ B()
    {
        cout<<"\nDerived class destructor";
    }
};

void test()
{
    A *ptr = new B;
    delete ptr;
}
int main()
{
    test();
    return 0;
}

OUTPUT:

Base class destructor

Example of Virtual Destructor:

#include<iostream>
using namespace std;
void test();
class A
{
private:
    int a;
public:
    virtual ~ A()
    {
        cout<<"\nBase class destructor";
    }
};
class B: public A
{
private:
    int b;
public:
    ~ B()
    {
        cout<<"\nDerived class destructor";
    }
};

void test()
{
    A *ptr = new B;
    delete ptr;
}
int main()
{
    test();
    return 0;
}

OUTPUT:

Derived class destructor
Base class destructor

0 comments:

Post a Comment