All Courses
OOP: CONSTRUCTORS AND DESTRUCTORS

Constructor vs Destructor

Constructors and destructors control object lifetime.

Feature Constructor Destructor
Purpose Initialize object Clean up object
Name Same as class Same as class with ~
Return type None None
Parameters Can have parameters Cannot have parameters
Overloading Can be overloaded Cannot be overloaded
Call timing When object is created When object is destroyed
In inheritance Base before derived Derived before base
Common use set valid starting state release resources

Lifecycle Example

#include <iostream>

class Demo {
public:
    Demo() {
        std::cout << "Constructor\n";
    }

    ~Demo() {
        std::cout << "Destructor\n";
    }
};

int main() {
    Demo object;
}

Output:

Constructor
Destructor

Inheritance Order

Construction:

Base constructor -> Derived constructor

Destruction:

Derived destructor -> Base destructor

Viva Answer

A constructor initializes an object when it is created, while a destructor cleans up an object when it is destroyed. Constructors can be overloaded and take parameters; destructors cannot take parameters and cannot be overloaded.

Quick Check

  • Which runs first: constructor or destructor?
  • Can constructors be overloaded?
  • Can destructors be overloaded?
  • What is destruction order in inheritance?