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
#include<iostreams.h>
class construct{
int a;
public:
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
ob1.show();
ob2.show();
}
Output:
100
20
100
20