constructors and destructors in cpp

9/13/2025

construcrs destructors in cpp

Go Back

Constructors and Destructors in C++ Tutorial

Introduction

Constructors and destructors are special member functions in C++ classes. They are used to initialize and clean up objects, respectively. Understanding these is crucial to writing efficient and bug-free C++ code.


construcrs  destructors in cpp

What is a Constructor?

A constructor is a special function that is automatically called when an object of a class is created. It is mainly used to initialize data members.

Key Points:

  • Same name as the class

  • No return type (not even void)

  • Can be overloaded

Example – Constructor in Developer Class

#include <iostream>
using namespace std;

class Developer {
public:
    string name;
    string skills;
    double salary;

    // Constructor
    Developer(string n, string s, double sal) {
        name = n;
        skills = s;
        salary = sal;
        cout << "Developer object created for " << name << endl;
    }

    void work() {
        cout << name << " is coding using " << skills << "." << endl;
    }
};

int main() {
    Developer dev1("Alice", "C++ and Python", 7000);
    dev1.work();

    Developer dev2("Bob", "Java and Spring Boot", 8000);
    dev2.work();

    return 0;
}

Output:

Developer object created for Alice
Alice is coding using C++ and Python.
Developer object created for Bob
Bob is coding using Java and Spring Boot.

What is a Destructor?

A destructor is a special function that is automatically called when an object goes out of scope or is deleted. It is used to free resources or perform cleanup tasks.

Key Points:

  • Same name as the class, but prefixed with ~

  • No parameters and no return type

  • Only one destructor per class (cannot be overloaded)

Example – Destructor in Developer Class

#include <iostream>
using namespace std;

class Developer {
public:
    string name;

    Developer(string n) {
        name = n;
        cout << "Developer object created for " << name << endl;
    }

    ~Developer() {
        cout << "Developer object destroyed for " << name << endl;
    }
};

int main() {
    Developer dev1("Alice");
    Developer dev2("Bob");
    return 0;
}

Output:

Developer object created for Alice
Developer object created for Bob
Developer object destroyed for Bob
Developer object destroyed for Alice

Benefits of Constructors and Destructors

  • Automation – Automatically handle setup and cleanup

  • Efficiency – Reduce errors by ensuring resources are properly initialized and released

  • Code clarity – Encapsulate initialization and cleanup logic within the class


Conclusion

Constructors and destructors are essential for managing object lifecycle in C++.

  • Constructor initializes an object.

  • Destructor cleans it up.

By using them, you ensure that resources are managed safely and efficiently in your C++ programs.