In this C++ tutorial, you will learn about constructors in a class, the default constructor, the parameterised constructor, with examples.

C++ Class Constructor

Constructor is a method in class, that is run during object creating. Constructor is used to initialise the state of an object, in other words, set specific values for its properties.

The name of constructor method must be same as that of class.

Based on the presence of parameters in the definition of constructor, there are two types of constructors. They are

  • Default Constructor
  • Parameterised Constructor

Default Constructor

The default constructor does not have any parameters. Inside this default constructor, we may specify default values for some or all of the properties for this object.

ADVERTISEMENT

Example

For example, in the following program, we have a class named A. It has two properties named p1 and p2. We have a default constructor A() where we set p1 and p2 with a default value of -1.

C++ Program

#include <iostream>
using namespace std;

class A {
public:
    int x;
    int y;
    
    A() {
        x = -1;
        y = -1;
    }
};

int main() {
    A obj = A();
    cout << "x : " << obj.x << endl;
    cout << "y : " << obj.y << endl;
}

Output

x : -1
y : -1
Program ended with exit code: 0

So, whenever we create an object of type A, with no parameters specified for the constructor, then those objects would have an initial value of -1 for the properties x and y.

Parameterised Constructor

The parameterised constructor must have one or more parameters. We may use these parameters to initialise the properties of this object.

Example

For example, in the following program, we have a class named A. It has two properties named p1 and p2. We have a parameterised constructor A(_x, _y) where we set x and y with these parameter values respectively.

C++ Program

#include <iostream>
using namespace std;

class A {
public:
    int x;
    int y;
    
    A(int _x, int _y) {
        x = _x;
        y = _y;
    }
};

int main() {
    A obj = A(3, 4);
    cout << "x : " << obj.x << endl;
    cout << "y : " << obj.y << endl;
}

Output

x : 3
y : 4
Program ended with exit code: 0

Therefore, whenever an object of type A is created using parameterised constructor, we are setting specific initial values for x and y.

Conclusion

In this C++ Tutorial, we learned what a constructor is, different types of constructors based on parameters, and how to use those constructors, with the help of examples.