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


Please Help Members By Posting Answers For Below Questions

If a header file is included twice by mistake in the program, will it give any error?

552


What are the types of array in c++?

620


What are the uses of static class data?

638


Describe Trees using C++ with an example.

608


write a function signature with various number of parameters.

567






How would you call C functions from C++ and vice versa?

640


What is c++ manipulator?

555


What are the two main components of c++?

591


Do you know what is overriding?

619


What is #include cstdlib in c++?

662


What is the difference between a definition and a declaration?

578


How do you clear a set in c++?

605


List down the guideline that should be followed while using friend function.

649


Which bit wise operator is suitable for turning off a particular bit in a number?

645


Where is atoi defined?

583