Introduction
Constructors and destructors are special functions in C++ used to control the creation and destruction of objects. A constructor initializes the object automatically when it is created, ensuring that the class variables and resources are correctly set up. A destructor, on the other hand, is called when an object goes out of scope or is deleted, and it is used to free up any resources the object was using. These functions are vital in object-oriented programming for automatic resource management, preventing memory leaks, and supporting clean initialization logic. Constructors can be overloaded, but destructors cannot be. Understanding their roles is critical for writing safe and maintainable C++ code.
Constructor in C++
A constructor is a special member function that shares the class name and is automatically called when an object of the class is created. Its main purpose is to initialize data members or allocate resources like memory. Constructors have no return type, not even void, and they can be overloaded to handle different initialization needs. If no constructor is defined, the compiler provides a default one.
General Syntax:
class ClassName {
public:
ClassName(); // Constructor declaration
};
Example:
class Student {
public:
Student() {
cout << “Object created successfully.”;
}
};
int main() {
Student s; // Constructor is called automatically
}