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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain the uses oof nested class?

617


How do you generate a random number in c++?

597


Define virtual constructor.

633


What is vector pair in c++?

703


Explain queue. How it can be implemented?

665






Define pure virtual function?

553


what kind of projects are suitable for c and c++

613


Inline parameters : What does the compiler do with the parameters of inline function, that can be evaluated in runtime ?

2005


When are exception objects created?

602


Differentiate between realloc() and free().

588


Do you know the use of vtable?

626


Write about the access privileges in c++ and also mention about its default access level?

606


Are iterators pointers?

658


Can we get the value of ios format flags?

655


Explain about vectors in c ++?

587