c-plus-plus
  1. c-plus-plus-constructor-vs-destructor-in-c

Constructor vs Destructor in C++

Constructors and destructors are two special member functions in a C++ class that are used to initialize and destroy objects of that class.

Syntax

class MyClass {
public:
    MyClass(); // constructor
    ~MyClass(); // destructor
};

The constructor has the same name as the class and is called automatically when an object is created. The destructor also has the same name as the class, but is preceded by a ~ (tilde) symbol and is called automatically when an object is destroyed.

Example

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass() {
        cout << "Constructor called" << endl;
    }
    ~MyClass() {
        cout << "Destructor called" << endl;
    }
};

int main() {
    MyClass obj;
    return 0;
}

Output

Constructor called
Destructor called

Explanation

In the above example, we have defined a class calledMyClass" with a constructor and destructor. We create an object of the class "MyClass" in the main function, which calls the constructor when it is created and the destructor when it is destroyed.

Use

Constructors are used to initialize the state of an object when it is created. This includes setting initial values for member variables, allocating memory, and initializing pointers. Constructors can also be overloaded to provide different ways of initializing objects.

Destructors are used to clean up the resources held by an object when it is destroyed. This includes deallocating memory, closing files, releasing locks, and any other cleanup that may be necessary.

Important Points

  • A constructor is called automatically when an object is created.
  • A destructor is called automatically when an object is destroyed.
  • Constructors are used to initialize the state of an object.
  • Destructors are used to clean up the resources held by an object.

Summary

In summary, constructors and destructors are two special member functions in a C++ class that are used to initialize and destroy objects of that class. Constructors are used to initialize the state of an object, while destructors are used to clean up resources held by an object.

Published on: