C++ Language



Admission Enquiry Form

  

Parameterized Constructor in C++:




What is Parameterized Constructor?

A constructor which has parameters is called parameterized constructor or we can say constructor with arguments.. 

 


Code for Parameterized Constructor in C++.

// C++ program to calculate the area of rectangle

#include <iostream>
using namespace std;
// declare a class
class Rectangle {
private:
float length;
float breath;

public:
// parameterized constructor to initialize variables
Rectangle(float len, float brth)
{
length = len;
breath = brth;
}
float calculateArea()
{
return length * breath;
}
};//end of class

int main() {
/*Object of Rectangle class with parameters
(this will call parameterized constructor)*/
Rectangle rect1(11.5,9.6);
Rectangle rect2(7.7,6.3);
cout << "Area of Rectangle 1: " << rect1.calculateArea() << endl;
cout << "Area of Rectangle 2: " << rect2.calculateArea();
return 0;
}


Output:

Area of Rectangle 1: 110.4
Area of Rectangle 2: 48.51