Rectangle friend function

Rectangle's friend function

Create a class Rectangle with the following private members: int width, int height.

Create a friend function calculate_area() that takes a Rectangle object as a parameter and calculates the area by accessing the private members width and height.

Answer

#include <iostream>

class Rectangle {
    friend int calculate_area(Rectangle& rect);  // Friend function declaration

private:
    int width;
    int height;

public:
    Rectangle(int w, int h) : width(w), height(h) {}
};

// Friend function definition
int calculate_area(Rectangle& rect) {
    return rect.width * rect.height;  // Accessing private members
}

int main() {
    Rectangle rect(10, 5);
    std::cout << "Area of the rectangle: " << calculate_area(rect) << std::endl;

    return 0;
}
Questions