1
Constructor and Destructor ★★★★★
OOP
A constructor has the same name as the class, no return type, and runs automatically when an object is created. A destructor (~ClassName) runs when the object is destroyed.
- Default constructor — no parameters.
- Parameterised constructor — takes arguments.
- Copy constructor — creates an object from another object:
Student(const Student &s). - Constructors can be overloaded; a destructor cannot (only one, no parameters).
class Student {
string name;
int roll;
public:
Student() : name("Unknown"), roll(0) {} // default
Student(string n, int r) : name(n), roll(r) {} // parameterised
Student(const Student &s) : name(s.name), roll(s.roll) {} // copy
~Student() { cout << name << " destroyed\n"; } // destructor
};
Student a; // default
Student b("Rahim", 7); // parameterised
Student c = b; // copy
Q & A
- Can a constructor be private?
Yes. It stops outside code from creating objects directly, used for example in the Singleton pattern. - Shallow vs deep copy?
A shallow copy copies pointer values, so both objects share the same memory. A deep copy allocates new memory and copies the data.