🏗️ Class-Based Constructors and Destructors in C++
Constructors and destructors are key components of object-oriented programming in C++. They help manage the lifecycle of class objects by initializing and cleaning up resources automatically.
📘 What is a Constructor?
A constructor is a special class function automatically invoked when an object is created. It has the same name as the class and no return type. Constructors are used to initialize object members.
💣 What is a Destructor?
A destructor is called automatically when an object goes out of scope or is deleted. It’s used to release resources like memory, files, or connections. A destructor's name is preceded by a tilde (~
).
📄 C++ Example: Constructor and Destructor
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Constructor: Object created" << endl;
}
~MyClass() {
cout << "Destructor: Object destroyed" << endl;
}
};
int main() {
MyClass obj; // Constructor is called
cout << "Inside main function" << endl;
return 0; // Destructor is called here
}
📝 Sample Output
Inside main function
Destructor: Object destroyed
🧠 Key Points
- Constructors are used to initialize class objects.
- Destructors handle object cleanup automatically.
- Only one destructor is allowed per class.
- Constructors can be overloaded, but destructors cannot.
By using constructors and destructors, your code becomes more efficient, readable, and memory-safe. This forms the foundation of object-oriented programming in C++.
Post a Comment