/* */ Click to Join Live Class with Shankar sir Call 9798158723

What is Parameterized Constructor in C++ ?


The parameterized constructor can be used to pass the arguments to the constructor. The arguments will help to initialize an object when it is created. It is used to provide different values to distinct objects.We can define more than one parameterized constructor according to the need of the user, but we have to follow the rules of the function overloading, like a different set of arguments must be there for each constructor.

Q.) Example of Parameterized constructor. in C++ to calculate the area of a wall ?
    


#include < ostream>
using namespace std;

// declare a class
class Wall {
  private:
    double length;
    double height;

  public:
    // parameterized constructor to initialize variables
    Wall(double len, double hgt) {
      length = len;
      height = hgt;
    }

    double calculateArea() {
      return length * height;
    }
};

int main() {
  // create object and initialize data members
  Wall wall1(10.5, 8.6);
  Wall wall2(8.5, 6.3);

  cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
  cout << "Area of Wall 2: " << wall2.calculateArea();

  return 0;
}
Output
Area of Wall 1: 90.3
Area of Wall 2: 53.55