Parameterized Constructor in C++ Example


A constructor is a special member function whose name is as that of its class name. It is used to initialize an object. A constructor has no return type. Whenever an object of a class is created, the constructor of the associated class is invoked automatically. A constructor can be overloaded i.e. there can be any number of constructors for a class. It is called as a constructor because it constructs the value of the data members of the class.

Different types of constructors are:

  • − Default Constructor: A constructor which never & doesn't accept any parameters.
  • − Parameterized Constructor: A constructor which accepts Parameters.
  • −For e.g.
  • class Abc {
  • int a,b;
  • public:
  • Abc(int i, int j) // parameterized constructor
  • };

Whenever a Parameterized Constructor is declared for a class, then while declaring objects, the corresponding arguments should be mandatorily passed. We can either call the parameterized constructor explicitly or implicitly.
Eg. for calling a constructor explicitly: Abc a1= Abc(112); Here an object a1 of class Abc is created and the values 30 and 40 are passed . to the object. Eg. for calling a constructor implicitly. Abc a1(30, 40);

Parameterized Constructor in C++ Example

#include<iostream> using namespace std; class Rbc{ int a; public: Rbc(int x){ cout<<"Parameterized Constructor is called"<<endl; a = x; } void print(){ cout<<"The value of a is"<<a<<endl; } }; int main(){ Rbc r1(8); r1.print(); return 0; }

Output:-

Parameterized Constructor is called
The value of a is :8

Explanation of the program:-

In this program, the parameterized constructor is invoked when the object r1 of class Rbc is created. The value passed is assigned to the class data member.