C++ Constructors

Welcome to The Coding College! In this tutorial, we’ll dive into constructors in C++. Constructors are special class methods used to initialize objects. They play a vital role in Object-Oriented Programming (OOP) by ensuring that objects are set up and ready for use immediately after creation.

What Is a Constructor?

A constructor is a special method that has the same name as the class and is automatically called when an object of the class is created.

  • It is used to initialize the object’s attributes.
  • It does not have a return type (not even void).

Syntax

class ClassName {
public:
    ClassName() {  
        // Constructor body
    }
};

Types of Constructors

C++ supports the following types of constructors:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor

1. Default Constructor

A default constructor takes no arguments and is used to initialize attributes with default values.

Example:

#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int year;

    // Default Constructor
    Car() {
        brand = "Unknown";
        year = 0;
    }

    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1;  // Default constructor is called
    car1.displayInfo();
    return 0;
}

Output:

Brand: Unknown, Year: 0  

2. Parameterized Constructor

A parameterized constructor accepts arguments to initialize attributes with specific values when the object is created.

Example:

#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int year;

    // Parameterized Constructor
    Car(string b, int y) {
        brand = b;
        year = y;
    }

    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1("Toyota", 2021);  // Pass arguments to the constructor
    Car car2("Ford", 2019);

    car1.displayInfo();
    car2.displayInfo();

    return 0;
}

Output:

Brand: Toyota, Year: 2021  
Brand: Ford, Year: 2019  

3. Copy Constructor

A copy constructor initializes an object by copying attributes from another object of the same class.

Example:

#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int year;

    // Parameterized Constructor
    Car(string b, int y) {
        brand = b;
        year = y;
    }

    // Copy Constructor
    Car(const Car &obj) {
        brand = obj.brand;
        year = obj.year;
    }

    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1("BMW", 2020);  // Parameterized constructor is called
    Car car2 = car1;        // Copy constructor is called

    car1.displayInfo();
    car2.displayInfo();

    return 0;
}

Output:

Brand: BMW, Year: 2020  
Brand: BMW, Year: 2020  

Constructor Overloading

You can overload constructors by defining multiple constructors with different numbers or types of parameters.

Example:

#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int year;

    // Default Constructor
    Car() {
        brand = "Unknown";
        year = 0;
    }

    // Parameterized Constructor
    Car(string b, int y) {
        brand = b;
        year = y;
    }

    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1;  // Default constructor
    Car car2("Tesla", 2023);  // Parameterized constructor

    car1.displayInfo();
    car2.displayInfo();

    return 0;
}

Output:

Brand: Unknown, Year: 0  
Brand: Tesla, Year: 2023  

Constructor with Default Parameters

A constructor can have default parameter values to make certain arguments optional.

Example:

#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int year;

    // Constructor with Default Parameters
    Car(string b = "Unknown", int y = 0) {
        brand = b;
        year = y;
    }

    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1;                // Uses default values
    Car car2("Audi", 2022);  // Passes arguments

    car1.displayInfo();
    car2.displayInfo();

    return 0;
}

Output:

Brand: Unknown, Year: 0  
Brand: Audi, Year: 2022  

Constructor in Practical Example

Here’s a practical use of constructors in a Student Management System:

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;
    string grade;

    // Parameterized Constructor
    Student(string n, int a, string g) {
        name = n;
        age = a;
        grade = g;
    }

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

int main() {
    Student student1("Alice", 20, "A");
    Student student2("Bob", 22, "B");

    student1.displayInfo();
    student2.displayInfo();

    return 0;
}

Output:

Name: Alice, Age: 20, Grade: A  
Name: Bob, Age: 22, Grade: B  

Destructor

A destructor is the opposite of a constructor. It is automatically called when an object goes out of scope or is deleted. Destructors are defined using the ~ symbol before the class name.

Example:

#include <iostream>
using namespace std;

class Car {
public:
    Car() {
        cout << "Constructor is called!" << endl;
    }

    ~Car() {
        cout << "Destructor is called!" << endl;
    }
};

int main() {
    Car car1;  // Constructor is called
    return 0;  // Destructor is called
}

Output:

Constructor is called!  
Destructor is called!  

Key Points About Constructors

  1. Automatic Call: Constructors are automatically invoked when an object is created.
  2. No Return Type: Constructors do not return any value.
  3. Name Matches Class: A constructor’s name must exactly match the class name.
  4. Overloading Allowed: Multiple constructors can be defined in a class.

Explore More at The Coding College

For more insights into C++ and other programming languages, visit The Coding College.

Leave a Comment