All Courses
OOP: CONSTRUCTORS AND DESTRUCTORS

What is a Constructor?

A constructor is a special member function that runs automatically when an object is created.

Its main job is to put the object into a valid starting state.

Basic Rules

  • The constructor name is the same as the class name.
  • It has no return type, not even void.
  • It is called automatically during object creation.
  • It is usually public.

Example

#include <iostream>
#include <string>

class Student {
private:
    std::string name;
    int marks;

public:
    Student() {
        name = "Unknown";
        marks = 0;
    }

    void display() const {
        std::cout << name << " scored " << marks << '\n';
    }
};

int main() {
    Student student; // constructor runs here
    student.display();
}

What Happens When an Object Is Created?

Think of object creation in this order:

storage is obtained -> data members initialize -> constructor body runs -> object is ready

Important: the constructor does not usually "create memory" by itself. The object storage is obtained before the constructor body runs. The constructor initializes that storage.

Why Constructors Matter

Without constructors, objects may start with invalid or unpredictable values.

Bad object state:

name = unknown garbage
marks = unknown garbage

Good object state:

name = "Unknown"
marks = 0

Constructor and OOP

Constructors protect object correctness from the beginning.

A well-designed class should make it hard to create an invalid object.

Viva Answer

A constructor is a special member function with the same name as the class and no return type. It is called automatically when an object is created, and its main purpose is to initialize the object into a valid state.

Quick Check

  • Does a constructor have a return type?
  • When is a constructor called?
  • What is the main purpose of a constructor?
  • Does the constructor body run before or after member initialization?