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
If a header file is included twice by mistake in the program, will it give any error?
What are the types of array in c++?
What are the uses of static class data?
Describe Trees using C++ with an example.
write a function signature with various number of parameters.
How would you call C functions from C++ and vice versa?
What is c++ manipulator?
What are the two main components of c++?
Do you know what is overriding?
What is #include cstdlib in c++?
What is the difference between a definition and a declaration?
How do you clear a set in c++?
List down the guideline that should be followed while using friend function.
Which bit wise operator is suitable for turning off a particular bit in a number?
Where is atoi defined?