Why would you make a destructor virtual?
Answer Posted / chandra
Vitual destructor is used
(1) whenever the base class object pointer points to
derived class object,and is being created using new.
i.e class base - base class
in main - base bptr;
class derived - derived class
in main - bptr = new derived();
Then whenever we use "delete bptr" at runtime always the
memory of bptr is freed but not derived because here the
pointer is of type base and not of derived.
Note: The destructor that gets invoked is the one that
associated with the type of the object.
Simple rule of thumb: Make your destructor virtual if your
class has any virtual functions.
Example:
#include <iostream.h>
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
virtual ~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;
}
| Is This Answer Correct ? | 9 Yes | 0 No |
Post New Answer View All Answers
How do you write a function that can reverse a linked-list?
Explain how a pointer to function can be declared in C++?
When do we run a shell in the unix system? How will you tell which shell you are running?
What is a constant reference?
Explain the virtual inheritance in c++.
What are pointer-to-members? Explain.
What is helper in c++?
What does namespace mean in c++?
What is private public protected in c++?
What are the effects after calling the delete this operator ?
Why c++ is created?
What are virtual constructors/destructors?
What is the output of the following program? Why?
What is fflush c++?
If you hear the cpu fan is running and the monitor power is still on, but you did not see anything show up in the monitor screen. What would you do to find out what is going wrong?