C++ Parameterized Constructor
A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values.
Syntax:
1 2 3 4 5 |
className(data-type argument){ // Constructor definition } |
1 2 3 4 5 |
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
1 2 3 |
Employee emp(101); |
2) Calling constructor explicitly
1 2 3 |
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‘.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#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:
1 2 3 |
Id=101 |
C++ Parameterize Constructor Example 2
We can create multiple parameterize constructor in a single class and called constructor as implicit or explicit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#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:
1 2 3 4 |
id=101 Dept=Programmer |