when can we use virtual destructor?

Answer Posted / richa

It is used whenever a base class pointer is pointing to its
derived class.In such a case when a user tries to delete the
base class pointer then it results in deallocating the
memory occupied by the base class.Therefore instead the
derived class getting destroyed the base class does.Now as
the base class gets destroyed the base class pointer which
was pointing to its derived class hold no meaning as it is
already destroyed.
n such a case we should make the destructors of the base
class virtual so that whenever a delete is called on the
base class pointer then as the destructor is virtual the
compiler will call the destructor of the respective derived
class.Hence the scenario wont be breached when a base class
pointe points to derived class as it would help deleting the
respective derived class object.

Is This Answer Correct ?    86 Yes 5 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How does work in c++?

594


What is a container class? What are the types of container classes in c++?

678


Why do we use the using declaration?

658


What is dev c++ used for?

603


Difference between pass by value and pass by reference?

597






What is static function? Explain with an example

560


Can we sort map in c++?

589


Refer to a name of class or function that is defined within a namespace?

603


What is singleton class in c++?

592


What is the difference between structure and class?

554


What does it mean to declare a member variable as static?

612


When to use “const” reference arguments in a function?

577


What is data hiding c++?

597


If I is an integer variable, which is faster ++i or i++?

588


What are maps in c++?

502