C++ - Constructors

In C++, constructors are special member functions of a class that are used to initialize objects of that class. Constructors are called automatically when an object is created and are responsible for setting initial values to the data members of the class. They ensure that objects are properly initialized before they can be used.

Constructors:

Constructors have the same name as the class and do not have a return type, not even void. They are used to initialize the data members of the class and perform any necessary setup operations. Constructors can be defined with different access specifiers (public, private, or protected) and can be overloaded to accept different parameter sets. A class can have multiple constructors. If a class does not have any explicitly defined constructors, the compiler generates a default constructor.

class Rectangle {
private:
    double length;
    double width;
public:
    Rectangle() {
        length = 0.0;
        width = 0.0;
    }
    Rectangle(double len, double wid) {
        length = len;
        width = wid;
    }
};

In this example, the Rectangle class has two constructors: a default constructor that takes no parameters and initializes the length and width to 0.0, and a parameterized constructor that takes two parameters (len and wid) and initializes the length and width based on the provided values.

Constructor Parameters:

Constructor parameters are variables defined within the parentheses after the constructor name. They allow you to pass values or objects to the constructor during object creation, enabling customization and initialization of objects based on specific values. Here's an example that demonstrates constructor parameters:

class Point {
private:
    int x;
    int y;
public:
    Point(int xPos, int yPos) {
        x = xPos;
        y = yPos;
    }
};

In this example, the Point class has a constructor that takes two parameters (xPos and yPos). During object creation, the provided values for xPos and yPos are used to initialize the x and y data members of the object.

Using Constructors:

Constructors are invoked automatically when an object is created. To create an object and invoke the constructor, you simply declare a variable of the class type, and the appropriate constructor is called based on the provided arguments. Here's an example:

int main() {
    Rectangle rectangle1;  // Invokes the default constructor
    Rectangle rectangle2(5.0, 3.0);  // Invokes the parameterized constructor
    return 0;
}

In this example, two objects of the Rectangle class are created. The first object, rectangle1, invokes the default constructor, which sets the length and width to 0.0. The second object, rectangle2, invokes the parameterized constructor by providing the values 5.0 and 3.0, which sets the length and width accordingly.