C++ Parameterized Constructor
A constructor having parameters is known as
parameterize constructor. Parameterize constructor is used to assign different values.
Syntax:
className(data-type argument){
// Constructor definition
}
className(data-type argument, data-type argument){
// Constructor definition
}
A parameterized constructor can be passed values to constructor function in two ways:
1) Calling constructor implicitly
Employee emp(101);
2) Calling constructor explicitly
Employee emp= Employee(101);
C++ Parameterize Constructor Example 1
Creating a class with the name '
Employee' and a parameterize constructor '
Employee(int)' which initialize data member '
id'.
#include <iostream>
using namespace std;
class Employee
{
int id;
public:
Employee(int x){
id=x;
}
void display(){
cout<<"id="<<id;
}
};
int main(){
Employee emp(101);
emp.display();
return 0;
}
Output:
C++ Parameterize Constructor Example 2
We can create multiple parameterize constructor in a single class and called constructor as implicit or explicit.
#include <iostream>
using namespace std;
class Employee
{
int id;
string dept;
public:
Employee(int x){
id=x;
}
Employee(string dep){
dept=dep;
}
void displayId(){
cout<<"id="<<id<<endl;
}
void displayDept(){
cout<<"Dept="<<dept<<endl;
}
};
int main(){
Employee emp1(101); //implicit
Employee emp2=Employee("Programmer"); //explicit
emp1.displayId();
emp2.displayDept();
return 0;
}
Output: