Destructor in C++

Destructor in C++

 A destructor in C++ is a special member function of a class that is automatically called when an object of that class goes out of scope or is explicitly destroyed. Destructor in C++ is used to clean up any resources or perform any necessary actions before the object is destroyed.

In C++, a destructor is a special member function of a class that is automatically invoked when an object goes out of scope or is explicitly deleted. It is used to free resources that the object may have acquired during its lifetime (like memory, file handles, database connections, etc.).

The syntax for a destructor in C++ is similar to that of a constructor, but with a tilde (~) followed by the class name.

Syntax:

class MyClass {

public:

    // Constructor

    MyClass() {

        // Initialization code

    }

    // Destructor

    ~MyClass() {

        // Cleanup code

    }

    // Other member functions and data members

};

The destructor does not have any parameters, and you can only have one destructor per class. The name of the destructor is always the same as the class name, preceded by a tilde.

The destructor(tilde operator(~)) is automatically called when an object is destroyed. This can happen when the object goes out of scope, such as when a local object is created inside a function and the function ends.

Here’s an Example of a Destructor in C++ :

#include <iostream.h>

class MyClass {

public:

    MyClass() {

        cout << “Constructor called” << endl;

    }

    ~MyClass() {

        cout << “Destructor called” << endl;

    }

};

int main() {

    MyClass obj;  // Create an object of MyClass

    // Other code…

    return 0;  // Object obj goes out of scope and the destructor is called

}

Destructor in C++
Destructor in C++
Destructor in C++
Destructor in C++

In the above example, when the object obj goes out of scope at the end of the main function, the destructor MyClass is automatically called. The destructor prints a message indicating that it has been called.

Example of a Destructor in C++

#include<iostream.h>

#include<conio.h>

class abc

{

public:

abc()

{

cout<<“constructor”;

}

~abc()

{

cout<<“destructor”;

}};

main()

{

clrscr();

abc ob1;

getch();

}

Destructor in C++
Destructor in C++

Key Points about Destructor in C++:


1. Name: Same as the class name, but preceded by a tilde ~.
2. No parameters → Destructor cannot be overloaded.
3. No return type (not even void).
4. Automatically called when:
           •  A local object goes out of scope.
           • A dynamically created object is deleted using delete.
5. Only one destructor per class.
6. Used mainly for cleanup work.

C++ Introduction

Constructors in C++