Skip to content
Home » Introduction to constructors

Introduction to constructors

🧱 Introduction to Constructors

A constructor is a special member function of a class that is automatically called when an object is created.

Its main purpose is to initialize objects.


Key Features of Constructors

  • Same name as the class name.
  • No return type, not even void.
  • Automatically invoked when an object is created.
  • Can be overloaded (multiple constructors with different parameters).

🧪 Example:

#include <iostream>
using namespace std;

class Student {
public:
int rollNo;

// Constructor
Student() {
rollNo = 101;
cout << "Constructor called!" << endl;
}

void display() {
cout << "Roll No: " << rollNo << endl;
}
};

int main() {
Student s1; // Constructor is called automatically
s1.display();
return 0;
}

🔍 Output:

Constructor called!
Roll No: 101

🔷 Types of Constructors

TypeDescription
Default ConstructorTakes no parameters.
Parameterized ConstructorTakes arguments to initialize data.
Copy ConstructorCreates a copy of another object.

1. Default Constructor

cppCopyEditclass A {
public:
    A() {
        cout << "Default constructor called!" << endl;
    }
};

2. Parameterized Constructor

class Student {
public:
int roll;

Student(int r) { // Constructor with parameter
roll = r;
}

void display() {
cout << "Roll No: " << roll << endl;
}
};

3. Copy Constructor

class Student {
public:
int roll;

Student(int r) {
roll = r;
}

// Copy constructor
Student(const Student &s) {
roll = s.roll;
}

void display() {
cout << "Roll: " << roll << endl;
}
};

📌 Why Use Constructors?

  • Ensures automatic initialization of objects.
  • Helps avoid writing extra code to initialize variables.
  • Makes code cleaner and safer.

🛑 Constructor vs. Member Function

FeatureConstructorMember Function
NameSame as classAny valid identifier
Return TypeNo return typeCan have return type
Call TimeCalled automaticallyCalled manually
PurposeInitializationPerform specific task

🧠 Real-Life Analogy

Think of a constructor like the initial setup process when you open a new smartphone:

  • Language, time zone, and Wi-Fi setup.
  • It happens automatically, once.
  • After setup, you can manually use different apps (like member functions).

🧾 Summary

  • A constructor initializes class objects.
  • It runs automatically when an object is created.
  • There are three main types: default, parameterized, and copy constructors.
  • Constructors help make code modular, reusable, and clean.