constructors and destructors in cpp
construcrs destructors in cpp
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.
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
#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.
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)
#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
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
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.