What is virtual destructor and how to use it?
Submitted by: AdministratorIf the destructor in the base class is not made virtual, then an object that might have been declared of type base class and instance of child class would simply call the base class destructor without calling the derived class destructor.
Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor.
class a
{
public:
a(){printf("nBase Constructorn");}
~a(){printf("nBase Destructorn");}
};
class b : public a
{
public:
b(){printf("nDerived Constructorn");}
~b(){printf("nDerived Destructorn");}
};
int main()
{
a* obj=new b;
delete obj;
return 0;
}
Output:
Base Constructor
Derived Constructor
Base Destructor
By Changing
~a(){printf("nBase Destructorn");}
to
virtual ~a(){printf("nBase Destructorn");}
Output:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
Submitted by: Administrator
Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor.
class a
{
public:
a(){printf("nBase Constructorn");}
~a(){printf("nBase Destructorn");}
};
class b : public a
{
public:
b(){printf("nDerived Constructorn");}
~b(){printf("nDerived Destructorn");}
};
int main()
{
a* obj=new b;
delete obj;
return 0;
}
Output:
Base Constructor
Derived Constructor
Base Destructor
By Changing
~a(){printf("nBase Destructorn");}
to
virtual ~a(){printf("nBase Destructorn");}
Output:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
Submitted by: Administrator
Read Online C++ Constructors Job Interview Questions And Answers
Top C++ Constructors Questions
☺ | Which of the following are NOT provided by the compiler by default? |
☺ | If the programmer does not explicitly provide a destructor, then which of the following creates an empty destructor? |
☺ | Constructors __________ to allow different approaches of object construction. |
☺ | What is shallow? |
☺ | It is a __________ error to pass arguments to a destructor. |
Top C Plus Plus Language Categories
☺ | C++ Pointers & Functions Interview Questions. |
☺ | C++ Operator Overloading Interview Questions. |
☺ | C++ Exception Handling Interview Questions. |
☺ | C++ Template Interview Questions. |
☺ | C++ Virtual Functions Interview Questions. |