Friend Functions Bridging Two Classes

Hard Static Members & Friend Functions PRO
🔒 Login to Unlock

Problem Statement

Create two classes: `Rectangle` (private `width`) and `Square` (private `side`). Define a global friend function `void compareArea(Rectangle r, Square s)` for both classes that compares their areas (`width*width` for Rectangle, `side*side` for Square). Print ‘Rectangle is larger’, ‘Square is larger’, or ‘Equal’. Read two integers (width, side), create both objects, and compare them.

Input Format

Two space-separated integers (width then side).

Output Format

Print the comparison result.

Constraints

Width and side >= 0

Sample Input

5 4

Sample Output

Rectangle is larger

Explanation

A single global friend function can be declared as a friend inside multiple different classes, bridging their private scopes.

Starter Code

#include <iostream>

class Square; // Forward declaration

class Rectangle {
    // Define private members, constructor, and friend declaration
};

class Square {
    // Define private members, constructor, and friend declaration
};

// Implement compareArea here

int main() {
    // Read inputs, create objects, and call compareArea
    return 0;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used