Constructor

Constructor is a special method which invoked automatically when we create a new instance. It is used to automatically initiate the values of fields present inside class. Constructor must always present inside a class and constructor name should be same as that of class name. There are 2 types of constructor when it comes to C++ programming language, let us see both with its definition below


CODE

EG 1 . Creating Rectangle class with constructor.

#include <iostream>
using namespace std;

class Rectangle {
  public:
    double length, width, height, density;
    //Constructor
    Rectangle(double l,double w,double h,double d) {
        length = l;
        width = w;
        height = h;
        density = d;
    }
    double Area() {
        return length * width;
    }
    double Perimeter() {
        return 2 * (length+width);
    }
    double Volume() {
        return Area() * height;
    }
    double Weight() {
        return Volume() * density;
    }
    void RectangleCalculation() {
        cout << Area() << endl;
        cout << Perimeter() << endl;
        cout << Volume() << endl;
        cout << Weight() << endl;
    }
};

int main() {
    //Invoking constructor with 4 arguments
    Rectangle wall(5, 6, 7, 2.8);
    wall.RectangleCalculation();
}



(Click Here, For more exercises)