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
the maximum length of a character constant can be a) 2 b) 1 c) 8
What is auto type c++?
How to get the current position of the file pointer?
Is c++ slower than c?
What is a volatile variable in c++?
What is the benefit of encapsulation?
Write a program using GUI concept for the scheduling algorithms in Operating system like SJF,FCFS etc..
What is the return value of the insertion operator?
What is the difference between multiple and multilevel inheritance in c++?
What are vectors used for in c++?
Do class declarations end with a semicolon? Do class method definitions?
Define Virtual function in C++.
Define a conversion constructor?
If dog is a friend of boy, and terrier derives from dog, is terrier a friend of boy?
Do you need a main function in c++?