Why and when is a virtual destructor needed?

Answer Posted / pradeep

This example fully describe the need of Virtual Destructor
in base class:-
----------------------------------------------------------
#include <iostream.h>
#include <stdio.h>
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
~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;
getch();
}

-----------------------------------------------------------
When it will be executed..it will show only that Base Class
destructor executed not the Derived.
But if we make Base class destructor "virtual"
(i.e. virtual ~Base(){ cout<<"Destructor : Base"<<endl;} )
then we can verify that Destructor execute into this order:--
1. Derived class destructor
2. Base class destructor

---If there is any mistake kindly let me know.
Thanks...!!!

Is This Answer Correct ?    11 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

c++ program to swap the objects of two different classes

1752


Is enum a class?

599


What is the use of oops?

614


What is a superclass in oop?

663


What is this pointer in oop?

548






How Do you Code Composition and Aggregation in C++ ?

24185


What is overloading and its types?

608


Why is it so that we can have virtual constructors but we cannot have virtual destructors?

3815


What is interface? When and where is it used?

1657


Why is object oriented programming so hard?

609


How is polymorphism achieved?

577


what is difference between class template and template class?

2152


What does and I oop and sksksk mean?

644


What do you mean by variable?

567


How do you define social class?

594