when can we use virtual destructor?

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 ?    14 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain explicit container.

821


What are move semantics?

850


To which numbering system can the binary number 1101100100111100 be easily converted to?

786


What are the c++ access specifiers?

1019


What is c++ course?

765






Should I learn c or c++ first?

808


Distinguish between new and malloc and delete and free().

738


write a program that withdrawals,deposits,balance check,shows mini statement. (using functions,pointers and arrays)

1997


What are references in c++? What is a local reference?

765


What is the meaning of string in c++?

755


List down the guideline that should be followed while using friend function.

809


Explain how the virtual base class is different from the conventional base classes of the opps.

876


What is iterator c++?

697


How do I use turbo c++?

707


Who created c++?

771