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
Explain the concept of copy constructor?
What is the best way to declare and define global variables?
How do you show the declaration of a virtual constructor?
What do the keywords volatile and mean mutable?
which of the following is not an secondary constant a) array b) real c) union
What do manipulators do?
What is meant by const_cast?
Write a program to show polymorphism in C++?
What new()is different from malloc()?
When should we use multiple inheritance?
What kind of problems can be solved by a namespace?
What do the header files usually contains?
Is there any difference between int [] a and int a [] in c++?
Are iterators pointers?
write asingle linked list which read from two list & the do the following 1 sort the prime & nonprime num (prime should be less tn nonprime) 2 each node has a prime num followd by nonprime 3 add a new node into its sutable plce 4 erase the most three duplicated non prime num 5 find the least duplicated prime num