9. Friend Function Access

#include <iostream>
#include <cstdint>
using namespace std;

class Register8 {
private:
    uint8_t value;
public:
    void setValue(uint8_t v) { value = v; }
    friend void printRegister(const Register8& r);
};

void printRegister(const Register8& r) {
    cout << "Register value = " << (int)r.value << "\n";
}

int main() {
    Register8 r;
    r.setValue(170);
    printRegister(r);
    return 0;
}

 

Solution Explanation

  • The variable value is private — normally, outside functions can’t see it.
  • By declaring friend void printRegister(const Register8&), that function gets special access.
  • printRegister() prints the private value directly.
     

Layman’s Terms

It’s like giving a spare key to a trusted friend — they can look inside even though it’s locked to everyone else.

 

Significance for Embedded Developers

In embedded drivers, friend functions can be used to:

  • Implement debugging utilities that need access to registers.
  • Write helper code without exposing private internals publicly.
  • Keep critical APIs private but still provide “backdoor” access for testing/logging.
     
Loading...

Input

Expected Output

Register value = 170