Write a C++ program using constructor

#include <iostream>
using namespace std;

class Rectangle {
  private:
    int length;
    int width;

  public:
    Rectangle(int l, int w) {
        length = l;
        width = w;
    }

    int getLength() {
        return length;
    }

    int getWidth() {
        return width;
    }
};

int main() {
    Rectangle rect(5, 10);
    cout << "Length: " << rect.getLength() << endl;
    cout << "Width: " << rect.getWidth() << endl;

    return 0;
}

Explanation:

  1. The program starts with the inclusion of the iostream library, which allows us to use input/output stream objects such as cout.

  2. The using namespace std; line allows us to use the standard library functions and objects without having to prefix them with std::.

  3. We define a class called Rectangle to represent a rectangle. The class has two private member variables: length and width.

  4. Inside the class, we define a constructor for the Rectangle class. The constructor takes two integer parameters l and w, which represent the length and width of the rectangle, respectively. The constructor initializes the length and width member variables with the values passed as arguments.

  5. We define two member functions getLength() and getWidth() inside the Rectangle class. These functions are used to retrieve the values of the length and width member variables, respectively.

  6. In the main() function, we create an instance of the Rectangle class called rect and initialize it with the values 5 and 10.

  7. We use the cout object from the iostream library to display the length and width of the rectangle using the getLength() and getWidth() member functions, respectively.

  8. Finally, we return 0 from the main() function to indicate successful program execution.