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

What are the features of oop?

645


Why is polymorphism needed?

609


Why is destructor used?

589


How long to learn object oriented programming?

580


What is methods in oop?

563






What are two types of polymorphism?

622


What is super in oop?

603


Describe these concepts: Polymorphism, Inheritance and Abstraction.

622


What is debug class?what is trace class? What differences are between them? With examples.

1617


What is and I oop mean?

630


What is inheritance and how many types of inheritance?

634


How do you achieve polymorphism?

622


What are the benefits of interface?

589


What is difference between abstraction and encapsulation?

598


Why is polymorphism used?

592