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

Are there interfaces in c++?

557


how to connect with oracle 9i with server in socket program in c/c++

1847


what is c++

1798


what is pre-processor in C++?

591


Of the numbers 12 23 9 28 which would be at the top of a properly implemented maxheap a) 28 b) 9 c) Any of them could be

925






Why is c++ called oops?

552


an operation between an integer and real always yeilds a) integer result b) real result c) float result

708


How does code-bloating occur in c++?

744


What are associate containers?

614


How do I run c++?

572


What is the this pointer?

633


What are the basic data types used in c++?

553


Explain what is oop?

619


Is c++ a software?

724


Is overriding possible in c++?

570