Home »
C++ programming language
Parameterized constructor in C++ with example
Learn: What is the parameterized constructor in C++ programming language? How to create parameterized constructor to initialize data members of a class?
In our last two posts, we have covered following two topics, if you didn't read them, I would recommend to read them first, the covered topics are:
In this post, we are going to learn parameterized constructor in C++ programming. As the name suggests it's a constructor with arguments/parameters, it follows all properties of the constructor and takes parameters to initialize the data.
For Example: If we want to initialize an object with some values while declaring it, we can do it creating parameterized constructors.
Let suppose there is a class named Person with two data members name and age, we can initialize the data members while creating the objects like this:
Person per1("Manikanth",21);
Person per2("Abhisekh", 19);
Consider this example: Here Demo is a class with three private data members A, B and C
#include <iostream>
using namespace std;
class Demo
{
private:
int A;
int B;
int C;
public:
//parameterized constructor
Demo(int A, int B, int C);
void set(int A, int B, int C);
void print();
};
Demo::Demo(int A, int B, int C)
{
this->A = A;
this->B = B;
this->C = C;
}
void Demo::set(int A, int B, int C)
{
this->A = A;
this->B = B;
this->C = C;
}
void Demo::print()
{
cout<<"Value of A : "<<A<<endl;
cout<<"Value of B : "<<B<<endl;
cout<<"Value of C : "<<C<<endl;
}
int main()
{
//Parameterized Constructor called when object created
Demo obj = Demo(1,1,1);
//here, 1,1,1 will be assigned to A,B and C
//printing the value
obj.print();
//changing the value using set function
obj.set(10,20,30);
//printing the values
obj.print();
return 0;
}
Output
Value of A : 1
Value of B : 1
Value of C : 1
Value of A : 10
Value of B : 20
Value of C : 30