Constructors & Destructors

Constructor, and destructor in C++.

* Constructors and destructors are special member functions that are used for initializing and cleaning up objects, respectively, in object-oriented programming (OOP).

Constructors

A constructor is a special member function with the same name as the class. It is automatically called when an object of the class is created. The purpose of a constructor is to initialize the object's state.

Default Constructor:

class MyClass {
public:
    // Default constructor
    MyClass() {
        // Initialization code goes here
    }
};

Parameterized Constructor:

class MyClass {
public:
    // Parameterized constructor
    MyClass(int x, int y) {
        // Initialization code using parameters
    }
};

Copy Constructor:

class MyClass {
public:
    // Copy constructor
    MyClass(const MyClass& other) {
        // Copy the state of 'other' object
    }
};

Destructors

A destructor is a special member function with the same name as the class, preceded by a tilde ('~'). It is automatically called when an object goes out of scope or is explicitly deleted. The purpose of a destructor is to release resources and clean up.

class MyClass {
public:
    // Destructor
    ~MyClass() {
        // Cleanup code goes here
    }
};

Now, let's create a simple program to see how contractors & contractors work in C++.

cpp Copy Code
#include<iostream>

class MyObject {
private:
    int data;

public:
    // Default constructor
    MyObject() {
        std::cout << "Default constructor called" << std::endl;
        data = 0;
    }

    // Parameterized constructor
    MyObject(int value) {
        std::cout << "Parameterized constructor called" << std::endl;
        data = value;
    }

    // Destructor
    ~MyObject() {
        std::cout << "Destructor called for data: " << data << std::endl;
    }
};

int main() {
    // Using constructors
    MyObject obj1;          // Default constructor
    MyObject obj2(42);       // Parameterized constructor

    // Destructor is automatically called when objects go out of scope
    // Destructor called for obj2, then obj1
    return 0;
                   
}
Output:
Default constructor called      
Parameterized constructor called
Destructor called for data: 42  
Destructor called for data: 0  

In the example above, the constructors are used to initialize objects, and the destructor is automatically called when the objects go out of scope at the end of the main function.

* Constructors initialize objects in C++, while destructors clean up resources when objects go out of scope. Pay attention to warning-free coding practices, such as using member initialization lists and ensuring proper initialization order.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.