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
Explain the uses oof nested class?
How do you generate a random number in c++?
Define virtual constructor.
What is vector pair in c++?
Explain queue. How it can be implemented?
Define pure virtual function?
what kind of projects are suitable for c and c++
Inline parameters : What does the compiler do with the parameters of inline function, that can be evaluated in runtime ?
When are exception objects created?
Differentiate between realloc() and free().
Do you know the use of vtable?
Write about the access privileges in c++ and also mention about its default access level?
Are iterators pointers?
Can we get the value of ios format flags?
Explain about vectors in c ++?