Lesson 47 of 60 – Constructors in C++
78%

Constructors in C++

A constructor is a special member function of a class that is automatically called when an object of the class is created. Constructors are mainly used to initialize objects and their data members.

Note: A constructor has the same name as the class and does not have a return type, not even void.

1. What is a Constructor?

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

class Student {

public:

    Student() {

        std::cout << "Constructor called";
    }
};

When an object of Student is created, the constructor is automatically called.

2. Constructor Syntax

The basic syntax of a constructor is:

class ClassName {

public:

    ClassName() {

        // initialization code

    }
};

The constructor name must exactly match the class name.

3. Constructor Has No Return Type

A constructor does not have a return type.

class Student {

public:

    Student() {

        std::cout << "Student object created";
    }
};

Do not write void before a constructor.

// Incorrect

void Student() {

}

4. Constructor is Called Automatically

#include <iostream>

class Student {

public:

    Student() {

        std::cout << "Constructor called";
    }
};

int main() {

    Student student;

    return 0;
}

When student is created, the constructor is automatically called.

5. Default Constructor

A constructor that takes no parameters is commonly called a default constructor.

class Student {

public:

    Student() {

        std::cout << "Default constructor";
    }
};

An object can be created without passing arguments:

Student student;

6. Constructor for Initializing Data

class Student {

private:

    std::string name;
    int age;

public:

    Student() {

        name = "Unknown";
        age = 0;
    }

    void display() {

        std::cout << name
                  << " "
                  << age;
    }
};

The constructor gives initial values to the object's data members.

7. Parameterized Constructor

A constructor that receives parameters is called a parameterized constructor.

class Student {

private:

    std::string name;
    int age;

public:

    Student(
        std::string n,
        int a
    ) {

        name = n;
        age = a;
    }
};

8. Using a Parameterized Constructor

Student student(
    "Amit",
    20
);

The values "Amit" and 20 are passed to the constructor.

The constructor can then use these values to initialize the object.

9. Constructor with Initializer List

C++ provides a constructor initializer list for initializing data members.

class Student {

private:

    std::string name;
    int age;

public:

    Student(
        std::string n,
        int a
    )
        : name(n), age(a) {
    }
};

Initializer lists are commonly used for direct member initialization.

10. Why Use Initializer Lists?

Initializer lists are especially important for certain members, such as references and const data members, and are commonly used for efficient direct initialization.

class Product {

private:

    std::string name;
    double price;

public:

    Product(
        std::string n,
        double p
    )
        : name(n), price(p) {
    }
};

11. Multiple Constructors

A class can have multiple constructors with different parameter lists.

class Student {

public:

    Student() {

        std::cout << "Default";
    }

    Student(int age) {

        std::cout << "Age: "
                  << age;
    }
};

This is an example of constructor overloading.

12. Constructor Overloading

Constructor overloading means defining multiple constructors in the same class with different parameter lists.

class Rectangle {

public:

    Rectangle() {

        std::cout << "Default rectangle";
    }

    Rectangle(int width, int height) {

        std::cout << "Rectangle: "
                  << width
                  << " x "
                  << height;
    }
};

13. Constructor with One Parameter

class Student {

private:

    int age;

public:

    Student(int a)
        : age(a) {
    }

    void display() {

        std::cout << age;
    }
};

int main() {

    Student student(20);

    student.display();

    return 0;
}

14. Constructor with Multiple Parameters

class Employee {

private:

    int id;
    std::string name;
    double salary;

public:

    Employee(
        int i,
        std::string n,
        double s
    )
        : id(i),
          name(n),
          salary(s) {
    }

    void display() {

        std::cout << id
                  << " "
                  << name
                  << " "
                  << salary;
    }
};

15. Constructor with Default Arguments

A constructor can have default argument values.

class Student {

private:

    std::string name;
    int age;

public:

    Student(
        std::string n = "Unknown",
        int a = 0
    )
        : name(n), age(a) {
    }
};

This allows the constructor to be called with fewer arguments.

16. Copy Constructor Introduction

A copy constructor creates a new object from an existing object of the same class.

class Student {

public:

    int age;

    Student(int a)
        : age(a) {
    }

    Student(const Student& other)
        : age(other.age) {
    }
};

17. Using a Copy Constructor

Student student1(20);

Student student2(student1);

std::cout << student2.age;

Here, student2 is initialized from student1.

For many classes, the compiler can generate an appropriate copy constructor automatically.

18. Constructor and const Data Member

A const data member should be initialized through the constructor initializer list.

class Student {

private:

    const int id;

public:

    Student(int studentId)
        : id(studentId) {
    }
};

The initializer list is important because a const data member cannot be assigned a new value after initialization.

19. Constructor and Reference Member

A reference data member must also be initialized using an initializer list.

class Student {

private:

    int& marks;

public:

    Student(int& m)
        : marks(m) {
    }
};

The reference member is connected to the referenced object during construction.

20. Constructor and Object Lifetime

A constructor runs when an object begins its lifetime.

class Demo {

public:

    Demo() {

        std::cout << "Object created"
                  << std::endl;
    }
};

int main() {

    Demo object;

    return 0;
}

The constructor is automatically invoked when object is created.

21. Constructor vs Normal Function

Constructor Normal Function
Same name as the class. Can have any valid function name.
Has no return type. Can have a return type.
Called automatically during object initialization. Normally called explicitly.
Used mainly to initialize objects. Used to perform operations.

22. Constructor and Private Members

Constructors can initialize private data members directly.

class BankAccount {

private:

    int accountNumber;
    double balance;

public:

    BankAccount(
        int number,
        double amount
    )
        : accountNumber(number),
          balance(amount) {
    }
};

This is a common way to initialize encapsulated object data.

23. Constructor with Validation

class Student {

private:

    int marks;

public:

    Student(int m) {

        if (m >= 0 && m <= 100) {

            marks = m;

        } else {

            marks = 0;
        }
    }

    int getMarks() const {

        return marks;
    }
};

A constructor can perform validation before storing values.

24. Constructor and Dynamic Objects

A constructor is also called when an object is created dynamically using new.

class Student {

public:

    Student() {

        std::cout << "Constructor called";
    }
};

int main() {

    Student* student =
        new Student();

    delete student;

    return 0;
}

Modern C++ generally prefers smart pointers for dynamic ownership, but this example demonstrates when the constructor is invoked.

25. Practical Student Constructor Program

#include <iostream>
#include <string>

class Student {

private:

    std::string name;
    int age;
    float marks;

public:

    Student(
        std::string n,
        int a,
        float m
    )
        : name(n),
          age(a),
          marks(m) {
    }

    void display() {

        std::cout << "Name: "
                  << name
                  << std::endl;

        std::cout << "Age: "
                  << age
                  << std::endl;

        std::cout << "Marks: "
                  << marks;
    }
};

int main() {

    Student student(
        "Amit",
        20,
        88.5
    );

    student.display();

    return 0;
}

26. Common Constructor Mistakes

  • Giving a constructor a return type.
  • Using a constructor name different from the class name.
  • Forgetting required constructor arguments.
  • Forgetting to initialize const or reference members properly.
  • Creating ambiguous overloaded constructors.
  • Confusing a constructor with a normal member function.
  • Using an initializer list incorrectly.

27. Constructor Overloading Example

class Rectangle {

private:

    int width;
    int height;

public:

    Rectangle()
        : width(0),
          height(0) {
    }

    Rectangle(int side)
        : width(side),
          height(side) {
    }

    Rectangle(
        int w,
        int h
    )
        : width(w),
          height(h) {
    }

    int area() const {

        return width * height;
    }
};

Different constructors allow objects to be initialized in different ways.

28. Best Practices for Constructors

  • Use constructors to establish a valid initial state for objects.
  • Prefer initializer lists for direct member initialization.
  • Use meaningful parameter names.
  • Keep constructor logic simple and clear.
  • Use constructor overloading only when different initialization forms are useful.
  • Initialize const and reference members through initializer lists.
  • Validate important input values when appropriate.
  • Make the object's initial state predictable.

29. Real-World Uses of Constructors

Constructors are widely used when creating objects in real-world applications.

  • Student: Initialize name, age, and marks.
  • Employee: Initialize ID, name, and salary.
  • Bank Account: Initialize account number and balance.
  • Product: Initialize product name, price, and quantity.
  • Book: Initialize title, author, and price.
  • Car: Initialize model, year, and other properties.

30. Constructors – Final Summary

Concept Meaning
Constructor A special member function used to initialize an object.
Constructor Name Must be the same as the class name.
Return Type A constructor has no return type.
Default Constructor A constructor that takes no arguments.
Parameterized Constructor A constructor that accepts parameters.
Initializer List Used for direct initialization of data members.
Constructor Overloading Multiple constructors with different parameter lists.
Copy Constructor Creates an object from another object of the same class.
class Student {

private:

    std::string name;
    int age;

public:

    Student(
        std::string n,
        int a
    )
        : name(n),
          age(a) {
    }

    void display() {

        std::cout << name
                  << " "
                  << age;
    }
};

int main() {

    Student student(
        "Amit",
        20
    );

    student.display();

    return 0;
}

📌 Key Points

  • A constructor is automatically called when an object is created.
  • A constructor has the same name as its class.
  • A constructor does not have a return type.
  • A default constructor takes no parameters.
  • A parameterized constructor receives values during object creation.
  • Constructor overloading allows multiple initialization methods.
  • Initializer lists are used for direct member initialization.
  • Const and reference members should be initialized through initializer lists.
  • A copy constructor creates an object from another object of the same class.
  • Constructors help establish a valid initial state for objects.

🧠 Quick Quiz

Question: Which statement about a C++ constructor is correct?