Constructors and Destructors
In C++ Object-Oriented Programming, constructors and destructors are special functions used to manage how objects are created and destroyed. They are automatically called when an object is created or deleted.
A constructor is a special member function that is called automatically when an object is created. It is used to initialize the object’s data members.
voidDefault Constructor
Takes no arguments. Used to assign default values.
class Student {
public:
int age;
Student() {
age = 18;
}
};
Parameterized Constructor
Takes arguments to initialize data with custom values.
class Student {
public:
int age;
Student(int a) {
age = a;
}
};
Copy Constructor
Initializes an object using another object of the same class.
class Student {
public:
int age;
Student(int a) { age = a; }
Student(const Student &s) {
age = s.age;
}
};
A destructor is a special member function that is called automatically when an object is destroyed. It is used to release memory or clean up resources used by the object.
class Student {
public:
Student() {
cout << "Constructor called" << endl;
}
~Student() {
cout << "Destructor called" << endl;
}
};
When an object of Student is created, the constructor runs automatically. When the object goes out of scope or is deleted, the destructor runs.
They help in writing efficient and safe code, especially when dealing with dynamic memory or external resources.
Open this section to load past papers