24 Nov 2019

  • November 24, 2019
  • Amitraj
Virtual Destructors in C++

A virtual destructor however, is pretty much feasible in C++. in fact, its use is often promoted in certain situations. One such situation is when we need to make sure that the different destructors in an inheritance hierarchy are called in order, particularly, when the base class pointer is reffering to a derived type object. it must be noted here that the order of calling of destructors in an inheritance hierarchy is opposite to that of constructors.

-> Destructors in the Base class can be Virtual. Whenever Upcasting is done, Destructors of the Base class must be made virtual for proper destrucstion of the object when the program exits.

NOTE: Constructors are never Virtual, only Destructors can be Virtual.


// C++ program on virtual destructor


#include<iostream>
using namespace std;
class Base
{
    public:
    virtual ~Base() 
    {
        cout << "Base Destructor\n"; 
    }
};

class Derived:public Base
{
    public:
    ~Derived() 
    { 
        cout<< "Derived Destructor"<<endl; 
    }
}; 

int main()
{
    Base* b = new Derived;     // Upcasting
    delete b;
    return 0;

}

OUTPUT:

Derived Destructor

Base Destructor


-> When we have Virtual destructor inside the base class, then first Derived class destructor is called and then Base class destructor is called, which is the desired behaviour.


Related Posts:

  • Dynamic memory (Runtime) Allocation and Deallocation operator in C++ Dynamic memory (Runtime) Allocation and Deallocation operator -> Programmers can dynamically allocate storage space while the program is running, but programmers cannot create new variable names "on the fly", and for th… Read More
  • Inline Function in C++ Inline Function in C++ -> To eliminate the cost of calls to small functions, C++ proposes a new feature called, Inline function.            An inline function is a function that is expanded… Read More
  • C++ Classes and Objects Class:- -> Language supports different data type like int, float, char, long, structure etc. Similar to that C++ supports class data type. -> A class is a user defined data type which has data members and member funct… Read More
  • Class Scope (C++ only) Class Scope in C++ -> A name declared within a member function hides a declaration of the same name whose scope extends to or past the end of the member function's class. -> When the scope of a declaration extends t… Read More
  • Default - Arguments in C++ Default - Arguments in C++ -> C++ allows us to call a function without specifying all its Arguments. -> In such a case, the function assigns a default value to the parameter which does not have a matching Argument in… Read More

Translate

Popular Posts