Destructor implemented by declaring a base class’s destructor with the keyword virtual is called a
virtual destructor. A virtual destructor ensures that, when delete is applied to a base class pointer or
reference, it calls the destructor implemented in the derived class, if an implementation exists.
Let’s take the simplest polymorphic relation: A - base class, B - class derived from A. If we've got a
pointer (or reference) to class A, but under the hood it is an object of type B, and we're trying to
delete the object, declaration of virtual destructor in class A ensures that the destructor of class B
will be called.
B* b = new B;
A* a = b //due to polymorphism!
delete a; // both A and B destructors are called.
virtual destructor. A virtual destructor ensures that, when delete is applied to a base class pointer or
reference, it calls the destructor implemented in the derived class, if an implementation exists.
Let’s take the simplest polymorphic relation: A - base class, B - class derived from A. If we've got a
pointer (or reference) to class A, but under the hood it is an object of type B, and we're trying to
delete the object, declaration of virtual destructor in class A ensures that the destructor of class B
will be called.
B* b = new B;
A* a = b //due to polymorphism!
delete a; // both A and B destructors are called.
Comments
Post a Comment
https://gengwg.blogspot.com/