Destructor in C++

 Destructor

 A destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted.

It is used to:

  • Release memory/resources
  • Close files/network connections
  • Clean up before object destruction

 

Syntax of Destructor

class ClassName {

public:

    ~ClassName() {

        // cleanup code

    }

};

 

Characteristics:

Property

Description

Name

Same as class but preceded by ~

Parameters

No parameters allowed

Return type

No return type (not even void)

Overloading

Not allowed

Virtual?

Yes, can be virtual (important in inheritance)


Functions

1: Local object going out of scope

2: When the program ends, and global objects are destroyed

3: During stack unwinding (exceptions)

If an exception occurs, destructors of already-constructed objects are automatically called.

 

Practical Example: Destructor to Free Memory

#include <iostream>

using namespace std;

 

class Demo {

    int* ptr;

 

public:

    Demo() {

        ptr = new int(10);

        cout << "Constructor: Memory allocated." << endl;

    }

 

    ~Demo() {

        delete ptr;

        cout << "Destructor: Memory freed." << endl;

    }

};

 

int main() {

    Demo d;

    return 0;    // destructor automatically runs

}

Output

Constructor: Memory allocated.

Destructor: Memory freed.


Summary

  • Destructor is an automatic cleanup function: same name as class prefixed with ~
  • No parameters, no return, cannot overload
  • Called when the object goes out of scope or when delete is used
  • In inheritance, destructors are called in reverse order
  • Use virtual destructor for polymorphic classes

=============================================================

Post a Comment

0 Comments