C++ Constructors


Introduction

A constructor in C++ is a special member function of a class that is automatically called when an object of the class is created. The primary purpose of a constructor is to initialize the object’s data members and set up its initial state. Constructors have the same name as the class and do not return a value.


1. What is a Constructor?

A constructor is a function that is automatically invoked when an object of a class is instantiated. Its primary role is to initialize the object’s properties (data members) and prepare it for use.

Key Points:

  • A constructor has the same name as the class.
  • A constructor does not return any value, not even void.
  • It is invoked automatically when an object is created.
  • Constructors can be overloaded, meaning a class can have multiple constructors with different parameters.

2. Types of Constructors

There are several types of constructors in C++:

1. Default Constructor:

A default constructor is a constructor that takes no arguments. It is called when an object is created without providing any arguments.

2. Parameterized Constructor:

A parameterized constructor is a constructor that takes arguments. It is used to initialize an object with specific values.

3. Copy Constructor:

A copy constructor is used to create a new object as a copy of an existing object. It initializes a new object by copying the values from another object of the same class.


3. Default Constructor

The default constructor is called when no arguments are passed while creating an object. If no constructor is explicitly defined, C++ provides a default constructor automatically.

Example 1: Default Constructor

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Default constructor
    Person() {
        name = "Unknown";
        age = 0;
        cout << "Default constructor called!" << endl;
    }

    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // Creating an object using the default constructor
    Person person1;
    person1.displayInfo();
    return 0;
}

Output:

Default constructor called!
Name: Unknown, Age: 0

Explanation:

  • The default constructor initializes the name and age data members to default values ("Unknown" and 0 respectively).
  • When person1 is created, the constructor is automatically invoked, and the object is initialized.

4. Parameterized Constructor

A parameterized constructor allows you to initialize an object with specific values when it is created. The constructor takes parameters, and the values passed to the constructor are used to initialize the data members.

Example 2: Parameterized Constructor

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Parameterized constructor
    Person(string n, int a) {
        name = n;
        age = a;
        cout << "Parameterized constructor called!" << endl;
    }

    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // Creating an object using the parameterized constructor
    Person person1("Alice", 30);
    person1.displayInfo();

    return 0;
}

Output:

Parameterized constructor called!
Name: Alice, Age: 30

Explanation:

  • The parameterized constructor takes two arguments: n (name) and a (age).
  • The constructor initializes the object with the values provided during object creation.

5. Copy Constructor

A copy constructor is a special constructor used to create a new object as a copy of an existing object. It is typically used when an object is passed by value to a function, returned by value from a function, or explicitly copied.

The copy constructor usually takes a reference to an object of the same class as a parameter.

Syntax for Copy Constructor:

ClassName(const ClassName &obj);

Example 3: Copy Constructor

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Parameterized constructor
    Person(string n, int a) {
        name = n;
        age = a;
        cout << "Parameterized constructor called!" << endl;
    }

    // Copy constructor
    Person(const Person &obj) {
        name = obj.name;
        age = obj.age;
        cout << "Copy constructor called!" << endl;
    }

    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // Creating an object using the parameterized constructor
    Person person1("John", 35);
    person1.displayInfo();

    // Creating a new object by copying person1
    Person person2 = person1;  // Copy constructor is called here
    person2.displayInfo();

    return 0;
}

Output:

Parameterized constructor called!
Name: John, Age: 35
Copy constructor called!
Name: John, Age: 35

Explanation:

  • The person1 object is created using the parameterized constructor.
  • The person2 object is created by copying person1 using the copy constructor.

6. Constructor Overloading

In C++, constructors can be overloaded, meaning you can have multiple constructors with different parameter lists. The correct constructor is selected based on the number and type of arguments passed at the time of object creation.

Example 4: Constructor Overloading

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Default constructor
    Person() {
        name = "Unknown";
        age = 0;
    }

    // Parameterized constructor
    Person(string n, int a) {
        name = n;
        age = a;
    }

    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // Using default constructor
    Person person1;
    person1.displayInfo();

    // Using parameterized constructor
    Person person2("Mike", 25);
    person2.displayInfo();

    return 0;
}

Output:

Name: Unknown, Age: 0
Name: Mike, Age: 25

Explanation:

  • The class Person has two constructors: a default constructor and a parameterized constructor.
  • Depending on the arguments passed, the appropriate constructor is called.

7. Constructor Initialization List

A constructor initialization list is an alternative way to initialize data members before entering the constructor body. This approach can be more efficient, especially when initializing constant data members or base class constructors.

Syntax:

ClassName::ClassName(parameters) : member1(value1), member2(value2) {
    // constructor body
}

Example 5: Constructor Initialization List

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Constructor with initialization list
    Person(string n, int a) : name(n), age(a) {
        cout << "Constructor with initialization list called!" << endl;
    }

    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Person person1("Jane", 28);
    person1.displayInfo();

    return 0;
}

Output:

Constructor with initialization list called!
Name: Jane, Age: 28

Explanation:

  • The constructor uses an initialization list to initialize the name and age data members before entering the constructor body.