C++ Destructors - C++ Programming Tutorial

C++ Destructors

BLUF: Mastering C++ Destructors is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Destructors

C++ is renowned for its efficiency. Learn how C++ Destructors enables low-level control and high-performance computing in the tutorial below.

In the realm of C++ programming, a destructor functions as the inverse of a constructor. Its purpose is to eliminate instances of classes. It is permissible to specify it only once within a class. Similar to constructors, the destructor is invoked automatically.

A destructor is essentially a special member function in a class that is called when an object is destroyed. It shares the same name as the class it belongs to, but is distinguished by the addition of a tilde (~) before the class name.

Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied to destructors.

Syntax

In C++ programming, each class comes with automatically provided destructors, although they can be redefined using the following syntax.

Example

~className(){

    // Body of destructor

}

Where the

  • tilde(~) symbol is employed to define the destructor of a className.

Just like any other method within the class, we have the option to define the destructor outside the class as well:

Example

className {

public:

     ~className();

}

class-name :: ~className() {

    // Desctructor Body

}

C++ Destructor Example

Let's consider an example to demonstrate the automatic invocation of the constructor and destructor in C++.

Example

Example

#include <iostream>  

using namespace std;    //using standard namespace

class Employee  

 {  

   public:  

        Employee()    

        {    

            cout<<"Constructor Invoked"<<endl;    

        }    

        ~Employee()    

        {    

            cout<<"Destructor Invoked"<<endl;    

        }  

};  

int main(void)   //main function

{  

    Employee e1; //creating an object of Employee   

    Employee e2; //creating an object of Employee  

    return 0;  

}

Output:

Output

Constructor Invoked

Constructor Invoked

Destructor Invoked

Destructor Invoked

Explanation:

In this instance, we are examining an Employee class containing both a constructor and a destructor. Upon instantiating two objects (e1 and e2) within the main function, the constructor is executed twice. Upon program termination, the destructor is automatically triggered for both objects, following the reverse sequence of their creation.

When do we have to write a user-defined destructor?

If we specify a destructor within a class, the compiler will automatically create a default destructor for our program. This default destructor works well unless the class involves dynamically allocated memory or pointers. In these situations, it is essential to implement a custom destructor to properly deallocate memory and avoid memory leaks.

User-defined Destructor Example in C++

Let's consider a scenario to demonstrate the user-defined destructor in C++.

Example

Example

#include <iostream>

#include <cstring>

using namespace std;  //using standard namespace

class Student {

    char* name; 

public:

    Student(const char* studentName) {

        name = new char[strlen(studentName) + 1]; 

        strcpy(name, studentName); 

        cout << "Constructor: Memory allocated for name\n";

    }

    ~Student() {

        delete[] name; 

        cout << "Destructor: Memory deallocated for name\n";

    }

    void display() {

        cout << "Student Name: " << name << endl;

    }

};

int main() {    //main function

    Student s1("David");

    s1.display();

    return 0;

}

Output:

Output

Constructor: Memory allocated for name

Student Name: David

Destructor: Memory deallocated for name

Explanation:

In this instance, we are examining a Student class that dynamically reserves memory for a name. Subsequently, a constructor duplicates the name, and the destructor releases the allocated memory. Within the main function, an instance named "David" is instantiated, displayed, and subsequently automatically managed for cleanup.

Virtual Destructors in C++

In C++, an ambiguous behavior known as a virtual destructor is primarily employed for deallocating a derived class object using a base class pointer object. The virtual keyword in the base class destructor guarantees that both the base class and the derived class destructors will be invoked during runtime. However, it initiates the execution of the derived class destructor first, followed by the base class destructor, to free up the memory occupied by both destructors.

Virtual Destructor Example in C++

Let's consider an example to demonstrate the concept of a virtual destructor in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class Base {

public:

    Base() {

        cout << "Base Constructor\n";

    }

    virtual ~Base() {  

        cout << "Base Destructor\n";

    }

};

class Derived : public Base {

public:

    Derived() {

        cout << "Derived Constructor\n";

    }

    ~Derived() {

        cout << "Derived Destructor\n";

    }

};

int main() {  //main function

    Base* ptr = new Derived(); 

    delete ptr; 

    return 0;

}

Output:

Output

Base Constructor

Derived Constructor

Derived Destructor

Base Destructor

Explanation:

In this instance, we are working with a base class containing a virtual destructor and a subclass that extends it. Subsequently, a base class pointer is directed towards a subclass object. The invocation of both subclass and base destructors occurs upon deletion since the base destructor is defined as virtual. As a result, the cleanup process in inheritance is executed accurately.

Pure Virtual Destructor

In C++ programming, a pure virtual destructor is a unique kind of destructor specified in an abstract base class using the = 0 syntax, similar to a pure virtual function. This declaration renders the class abstract, preventing the instantiation of objects from it. Despite being declared as pure, a destructor must still include a body (definition) since destructors are invariably invoked during object destruction.

The key difference between Virtual and Pure Virtual Destructors lies in the fact that a pure virtual destructor will mark its Base class as Abstract, preventing the instantiation of objects from that class. Derived classes do not need to provide implementations for pure virtual destructors.

Pure Virtual Destructor Example in C++

Let's consider an example to demonstrate the concept of a pure virtual destructor in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;   //using standard namespace

class Base {

public:

    virtual ~Base() = 0;  //pure virtual destructor

};

Base::~Base() {

    cout << "Base destructor called\n";

}

class Derived : public Base {

public:

    ~Derived() {

        cout << "Derived destructor called\n";

    }

};

int main() {    //main function

    Base* ptr = new Derived();

    delete ptr;

    return 0;

}

Output:

Output

Derived destructor called

Base destructor called

Explanation:

In this illustration, we showcase the implementation of a pure virtual destructor within the base class, rendering it abstract. Subsequently, the destructor is defined externally to the class to guarantee effective cleanup. Deleting a Derived object through a Base pointer invokes both destructors in the appropriate sequence, thereby maintaining secure destruction.

Features of Destructor in C++

Several features of a destructor in C++ are as follows:

  • Destructor name should be the same as their class name with a tilde (~) symbol prefixed.
  • It cannot be defined more than once.
  • Destructor is only one method of terminating the object formed by the constructor. So the destructor can't be overloaded.
  • It cannot be declared as static or constant.
  • The destructor doesn't take any argument and also doesn't return any value.
  • It is invoked automatically when an object goes out of scope.
  • Destructors free the memory space that is held by the objects that the constructor created.
  • In the destructor, objects are destroyed in the reverse order of their creation.
  • When the destructor is executed?

A destructor function is automatically invoked when the object goes out of scope or is deleted. There are several cases when we call the destructor in C++.

  • In C++ programming, a destructor is invoked when the function ends.
  • A destructor is invoked when a block that holds local variables is finished.
  • Destructor is invoked when a delete operator is invoked.
  • C++ Destructors FAQs

    1) What is a destructor in C++?

In C++, a destructor is a unique member function that is automatically invoked when an object goes out of scope or is deleted, primarily employed to release allocated resources.

2) When is a destructor invoked?

It gets triggered automatically when an object needs to be destroyed, either upon going out of scope or when delete is called.

3) Can we contain more than one destructor in a class in C++?

No, a class can have only a single destructor, and it is not possible to overload it.

4) What does the syntax of a destructor look like in C++?

It consists of a tilde (~) followed by the class name: ~ClassName.

5) What is a virtual destructor in C++?

In C++, a virtual destructor represents behavior that is not defined, serving the purpose of deleting an object of a derived class through an object pointer of the base class.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience