Why would you make a destructor virtual?

Answer Posted / chandra

Vitual destructor is used

(1) whenever the base class object pointer points to
derived class object,and is being created using new.
i.e class base - base class
in main - base bptr;
class derived - derived class
in main - bptr = new derived();

Then whenever we use "delete bptr" at runtime always the
memory of bptr is freed but not derived because here the
pointer is of type base and not of derived.

Note: The destructor that gets invoked is the one that
associated with the type of the object.

Simple rule of thumb: Make your destructor virtual if your
class has any virtual functions.

Example:
#include <iostream.h>
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
virtual ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"<<endl;}
~Derived(){ cout<<"Destructor : Derived"<<endl;}
};
void main()
{
Base *Var = new Derived();
delete Var;
}


Is This Answer Correct ?    9 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

write asingle linked list which read from two list & the do the following 1 sort the prime & nonprime num (prime should be less tn nonprime) 2 each node has a prime num followd by nonprime 3 add a new node into its sutable plce 4 erase the most three duplicated non prime num 5 find the least duplicated prime num

2298


Can the operator == be overloaded for comparing two arrays consisting of characters by using string comparison?

649


What is the use of setprecision in c++?

621


Why is c++ still used?

697


What is the return value of the insertion operator?

714






What is a friend function in c++?

671


Are vectors faster than arrays?

654


Write a program to find the Fibonacci series recursively.

710


What is data type in c++?

650


Explain how a pointer to function can be declared in C++?

659


Explain the difference between realloc() and free() in c++?

635


What is the fastest c++ compiler?

663


What is the difference between containment and delegation?

822


What is data abstraction? How is it different from data encapsulation?

617


What are the two shift operators and what are their functions?

668