Understanding Constructors in C++

  • Last updated Apr 25, 2024

A class constructor is a special block of code that is automatically invoked when an object is created. Constructors are primarily used to initialize class variables with either default or user-defined values. The constructor's name is the same as the class name, and they do not have a return type.

Types of Constructors

There are 3 types of constructors in C++:

  1. Default Constructors:
  2. A default constructor has no parameters and provides default values for class variables. It is also called a zero-argument constructor. It is automatically called when an object is created without arguments.

    Example:

    #include <iostream>
    
    class MyClass {
    public:
        int value;  // Data member
    
        // Default constructor (implicitly provided by the compiler)
    };
    
    int main() {
        MyClass obj;  // Creating an object of MyClass using the default constructor
    
        // Accessing the value data member (Note: it won't be explicitly initialized)
        std::cout << "Default value: " << obj.value << std::endl;
    
        return 0;
    }

    In this example, we have a class MyClass with an integer data member value. Since we haven't defined any constructors explicitly, C++ provides a default constructor for us. When we create an object of MyClass using MyClass obj;, the default constructor is called, and value is not explicitly initialized, so it contains a default value (usually garbage).

    It's important to note that if you define any constructor explicitly (including a parameterized constructor), the compiler will not provide a default constructor. If you want to keep the default constructor while also defining other constructors, you can explicitly define the default constructor:

    class MyClass {
    public:
        int value;
    
        // Explicitly defining a default constructor
        MyClass() {
            value = 0; // Set a default value
        }
    };

    In this case, the default constructor has been provided with an explicit default value for the value data member.

  3. Parameterized Constructors:
  4. Parameterized constructors accept arguments, and they are especially useful when you need to initialize class variables with user-defined values.

    Example:

    #include <iostream>
    
    class Rectangle {
    public:
        int length;
        int width;
    
        // Parameterized constructor
        Rectangle(int l, int w) {
            length = l;
            width = w;
        }
    
        int calculateArea() {
            return length * width;
        }
    };
    
    int main() {
        // Creating objects of the Rectangle class using the parameterized constructor
        Rectangle rect1(6, 4);  // Object with length 5 and width 3
        Rectangle rect2(5, 7);  // Object with length 4 and width 6
    
        // Calculate and display the areas
        std::cout << "Area of rect1: " << rect1.calculateArea() << std::endl;
        std::cout << "Area of rect2: " << rect2.calculateArea() << std::endl;
    
        return 0;
    }

    In this example, we have a class called Rectangle with a parameterized constructor that takes two integers (l for length and w for width) as parameters. When objects rect1 and rect2 are created, the parameterized constructor is used to initialize their length and width data members with the specified values.

    Using parameterized constructors, you can create objects with specific initial values, making it more flexible and useful for various scenarios.

    The output of the above code isa as follows:

    Area of rect1: 24
    Area of rect2: 35
  5. Copy Constructors:
  6. Copy constructors are used to create a new object as a copy of an existing object. They ensure that the new object is an exact replica of the original.

    Example:

    #include <iostream>
    using namespace std;
    
    class Rectangle
    {
    private:
        double length;
        double height;
    
    public:
        // initializing variables with parameterized constructor
        Rectangle(double len, double hgt)
        {
            length = len;
            height = hgt;
        }
    
        // copying constructor with a Rectangle object as parameter
        // copies data of the obj parameter
        Rectangle(Rectangle &obj)
        {
            length = obj.length;
            height = obj.height;
        }
    
        double calculateArea()
        {
            return length * height;
        }
    };
    
    int main()
    {
        // creating an object of Rectangle class
        Rectangle rectangle1(7, 9);
    
        // copying contents of rectangle1 to rectangle2
        Rectangle rectangle2 = rectangle1;
    
        // printing areas of rectangle1 and rectangle2
        cout << "Area of Rectangle 1: " << rectangle1.calculateArea() << endl;
        cout << "Area of Rectangle 2: " << rectangle2.calculateArea();
    
        return 0;
    }

    In this example, we have a Rectangle class with two constructors: a parameterized constructor that accepts len for length and hgt for height as parameters, and initializes the length and height data members. The copy constructor takes a Rectangle object obj as a parameter and copies the data (length and height) from obj into the new object.

    In the main function, an object rectangle1 of the Rectangle class is created with a length of 7 and a height of 9 using the parameterized constructor. The object rectangle2 is created and initialized by copying the contents of rectangle1, demonstrating the use of the copy constructor. This code serves as a simple example of how constructors, including copy constructors, can be used to create and initialize objects of a class.

    The output of the above code is as follows:

    Area of Rectangle 1: 63
    Area of Rectangle 2: 63