example2_friend_class.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

class Square; // Forward declaration

class Rectangle {
private:
    double width;
    double height;

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

    // Declaring Square as a friend class
    friend class Square;

    double getArea() const {
        return width * height;
    }
};

class Square {
private:
    double side;

public:
    Square(double s) : side(s) {}

    // This method can access private members of Rectangle
    bool isLargerThan(const Rectangle& rect) const {
        double squareArea = side * side;
        return squareArea > (rect.width * rect.height);
    }
};

int main() {
    Rectangle rect(4.0, 5.0);
    Square square(4.5);

    std::cout << "Rectangle area: " << rect.getArea() << std::endl;
    std::cout << "Is square larger? " << (square.isLargerThan(rect) ? "Yes" : "No") << std::endl;

    return 0;
}
Back to friend