In this guide, we will demonstrate how to use parameterized constructors in C++.
Parameterized Constructor in C++
In C++, a constructor that takes one or more parameters is known as a parameterized constructor. When making a single instance of a class, it enables users to initialize an object’s data members using certain values. A parameterized constructor gives developers more flexibility when initializing objects with various values than the standard constructor, which accepts no inputs.
Syntax
The general syntax of the parameterized constructor is provided below:
public:
my_Class(parameter1, parameter2, ... ) {
}
// Data members and member functions.
};
According to the above-specified code block, the “my_Class” class is defined which has a public access specifier and a parameterized constructor (which uses the same name as the class name), and it takes arguments as “parameter1, parameter2, …”. Users can specify parameters in the constructor body to carry out initialization or any other necessary activities.
Example
At first specified the “<iostream>” header file:
The “<iostream>” is used to display user input and output with the help of standard classes, such as the input stream, and output stream, respectively.
In the provided code block, we have defined the “CircleArea” class, which is used to compute the area of a circle. To hold the radius of the circle, the class has a private member double data type variable named “radius”. The class has a parameterized constructor “CircleArea” that accepts a double value “r1” and allocates it to the “radius” member variable. After that, there is a member function called “calculateArea()” in the class that calculates the area of a circle using the formula “3.14 * radius * radius“. The calculated area is returned as a double value:
private:
double radius;
public:
CircleArea(double r1) {
radius = r1;
}
double calculateArea() {
return 3.14 * radius * radius;
}
};
In the “main()” function, we initialized the “CircleArea” class by passing a “radius” value of “5.0” to the parameterized constructor “CircleArea”. Then, in that instance, invoke the “calculateArea()” function to get the “total_area” of the circle:
CircleArea myCircle(5.0);
double total_area = myCircle.calculateArea();
std::cout << "Area of the circle: " << total_area << std::endl;
return 0;
}
Output
This demonstration provided detailed information on the parameterized constructor in C++.
Conclusion
In C++, the parameterized constructor is a feature that enables objects to be created with some specific initial values. Unlike requiring explicit setter methods or separate initialization routines, they offer a straightforward way to set the initial state of an object. In this tutorial, we have explained the parameterized constructor in C++.