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 linear search.
What are the operators in c++?
What is the cout in c++?
Which programming language is best?
How should runtime errors be handled in c++?
What is #include iostream in c++?
Describe private, protected and public – the differences and give examples.
What it is and how it might be called (2 methods).
Keyword mean in declaration?
Name the debugging methods that are used to solve problems?
Does there exist any other function which can be used to convert an integer or a float to a string?
What is helper in c++?
State the difference between delete and delete[].
What is lambda in c++?
Explain what is polymorphism in c++?