Q:

When to use virtual destructors in c++?

0

When to use virtual destructors?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

When we will delete an object of the derived class using a pointer to the base class that has a non-virtual destructor a results in undefined behavior.

So virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to the base class. Let see an example code,

#include<iostream>
using namespace std;
class base
{
public:
    base()
    {
        cout<<"Constructing base \n";
    }
    virtual ~base()
    {
        cout<<"Destructing base \n";
    }
};
class derived: public base
{
public:
    derived()
    {
        cout<<"Constructing derived \n";
    }
    ~derived()
    {
        cout<<"Destructing derived \n";
    }
};
int main()
{
    derived *d = new derived();
    base *b = d;
    delete b;
    return 0;
}

Output:

Constructing base
Constructing derived
Destructing derived
Destructing base

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now