Friend Functions (Accessing Private Data)

Medium Static Members & Friend Functions
Solve in Playground →

Problem Statement

Create a `Box` class with a private integer `width`. Provide a parameterized constructor to set the width. Declare a friend function `void printWidth(Box b)` inside the class. Implement the friend function outside to access the private width and print ‘Width: [w]’. Read an integer, instantiate the object, and call the friend function.

Input Format

A single integer.

Output Format

Print the width using the friend function.

Constraints

None

Sample Input

15

Sample Output

Width: 15

Explanation

A friend function is a standalone function that is granted full access to a class's private and protected members.

Starter Code

#include <iostream>

class Box {
private:
    int width;
public:
    // Define constructor and declare friend function
};

// Implement friend function printWidth here

int main() {
    // Read input, instantiate Box, and call printWidth
    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