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 that 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 program

#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.

This article is written by our awesome writer
Comments to: Parameterized Constructor in C++ with Example

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password