What is parameterized constructor? Give an example.

Parameterized Constructor: We know that when we create an object the constructor function gets execution automatically. Consider the following lines of codes,

constructor(){   //this is the constructor function
    a=1;     //initializing

void main(){
    constructor ob1,ob2;

When this executed the value of ‘a’ for both ob1 and ob2 sets to 1. But when we want different value of ‘a’ we will have to use parameterized constructor. Here while creating objects we will give them parameter as follows,

constructor(int i){   //this is the constructor function
    a=i;      //initializing

void main(){
    constructor ob1(5),ob2(10);

When executing, the value of ‘a’ for ob1 will be 5 and that for ob2 will be 10. A full example is given below,

//The parameterized constructor

class construct{
 int a;
  construct(int x){    //it has parameter
   a=x;      //setting the received value to a
  void show(){
   cout<<a<<"\n";  //printing a of caller object

void main(){
 construct ob1(100),ob2(20);//ob1 sending 100 and ob2 sending 20


Author: Tanmay Chakrabarty

Tanmay Chakrabarty is a former CSE student, currently working as a Senior Software Engineer with 5+ years of experience in the field of Web Application development in PHP+MySQL platform with strong skills in Javascript, JQuery, JQuery UI and CSS. He tries to write notes every week but fails due to heavy loads of duty.

Recommended Recommends


Contact Us