C++ Code Example: Area of ​​a Rectangle

In this code example, the area of a rectangle is calculated. First, a class named “Rectangle” is created. The class function getArea() performs the actual calculation. The print() function ensures the screen output. Finally, objects of the class Rectangle are created. The class functions are called via these objects.

#include <iostream>
using namespace std;

class Rectangle {
  public:
    int length, width;

    int getArea() {
        return length * width;
    }

    void print() {
        cout << "the rectangle has the length: " << length << " and the width: " << width << endl;
        cout << "Area: " << getArea() << endl;
    }
};

int main() {
    Rectangle r1;
    Rectangle r2;

    r1.length = 5;
    r1.width = 7;
    r2.length = 8;
    r2.width = 9;

    r1.print();
    r2.print();

    return 0;
}

Code Explanation

Defining the Rectangle Class

Class Declaration
class Rectangle {
  public:
    int length, width;

The Rectangle class is declared with two public member variables: length and width.

Member Functions

Calculating Area
int getArea() {
    return length * width;
}

The getArea function calculates the area of the rectangle by multiplying its length and width.

Printing Details
void print() {
    cout << "the rectangle has the length: " << length << " and the width: " << width << endl;
    cout << "Area: " << getArea() << endl;
}

The print function outputs the rectangle’s dimensions and area to the console.

Main Function

Object Creation
Rectangle r1;
Rectangle r2;

Two objects, r1 and r2, of the Rectangle class are created.

Setting Dimensions

r1.length = 5;
r1.width = 7;
r2.length = 8;
r2.width = 9;

The dimensions for r1 and r2 are set directly by accessing their public member variables.

Printing Details

r1.print();
r2.print();

The print function is called on both r1 and r2 to display their dimensions and area.

Output

the rectangle has the length: 5 and the width: 7
Area: 35
the rectangle has the length: 8 and the width: 9
Area: 72