Skip to main content

Most Visited Blog

How to Install minGW C++ compiler for Windows - Cyborg Coding

Parameterized Constructor in C++ with example - Cyborg Coding

A parameterized constructor in C++ is a constructor that takes one or more parameters. It is automatically called when an object of a class is created with arguments. The parameterized constructor can initialize the object's properties with the values passed as arguments. This allows for more flexibility and control when creating objects of a class, as the properties of the object can be set to specific values.

For example:

class MyClass {
private:
    int x;
    int y;
public:
    MyClass(int xVal, int yVal) {
        x = xVal;
        y = yVal;
    }
    int getX() { return x; }
    int getY() { return y; }
};

In this example, "MyClass" has a parameterized constructor that takes two parameters, "xVal" and "yVal". The constructor initializes the properties "x" and "y" to the values passed as arguments.

MyClass myObject(10,20);

This creates an object of the "MyClass" class, and the parameterized constructor is called, initializing the properties "x" and "y" to 10 and 20 respectively.

The parameterized constructor also allows for constructor overloading. Constructor overloading is a technique that allows a class to have multiple constructors with different parameters. The constructor that is called depends on the arguments passed when the object is created.

For example:

class MyClass {
private:
    int x;
    int y;
public:
    MyClass() {
        x = 0;
        y = 0;
    }
    MyClass(int xVal) {
        x = xVal;
        y = 0;
    }
    MyClass(int xVal, int yVal) {
        x = xVal;
        y = yVal;
    }
    int getX() { return x; }
    int getY() { return y; }
};

In this example, "MyClass" has three constructors: a default constructor with no parameters, a constructor that takes one parameter, "xVal" and a constructor that takes two parameters, "xVal" and "yVal". The constructor that is called depends on the arguments passed when the object is created.

MyClass myObject1;
MyClass myObject2(10);
MyClass myObject3(10,20);

In this example, myObject1 is created with the default constructor and initializes x and y to 0, myObject2 is created with the constructor that takes one parameter and initializes x to 10 and y to 0 and myObject3 is created with the constructor that takes two parameter and initializes x to 10 and y to 20.

Comments