MODULE 6: OBJECT-ORIENTED PROGRAMMING (OOP) 6.8 C++ Friend Functions and Friend Classes (Accessing Private Members, Controlled Coupling)

Industrial reference manual: Comprehensive architectural breakdown of C++ Friend Functions and Friend Classes, intentional encapsulation breaching, friend declarations, inter-class communication, and 10 production-aligned real-world implementations with outputs.

🤝 Mastering Friend Mechanisms: Controlled Access to Private State

Encapsulation dictates that private and protected members of a class are strictly hidden from outside code. However, there are scenarios where trusted external functions or entire peer classes require access to private implementation details. In C++, this is accomplished using the `friend` keyword.

🤝 Friend Functions

  • Non-Member Access: A standalone function declared with `friend` inside a class can access private and protected variables.
  • No `this` Pointer: Friend functions do not belong to the class scope and lack an implicit `this` pointer.
  • Common Use Cases: Binary operator overloading (e.g., stream insertion `<<`) and cross-class mathematical operations.

🏢 Friend Classes

  • Complete Access: Declaring an entire class as a friend (`friend class Auditor;`) grants all its member functions access to the private state of the host class.
  • One-Way Relationship: Friendship is neither inherited nor reciprocal (if Class A is a friend of Class B, Class B is not automatically a friend of Class A).

📊 End-to-End Friend Declaration & Private State Inspection Workflow Diagram

1. Class Definition

Define host class with private data members.

→

2. Friend Declaration

Declare external function or class as `friend` inside class scope.

→

3. Access Bypass

Compiler grants friend entity permission to read/write private attributes.

↓

6. Console Rendering

Output computation results via `std::cout` stream.

←

5. Encapsulation Shield

Non-friend external code remains blocked from accessing private state.

←

4. Friend Invocation

Friend function or class method accesses private state directly.

1. Bank Account Auditing (Friend Function Accessing Private Balance)
A standalone friend audit function accesses private account balances to compute statutory reserve requirements.
C++ / Friend Audit Function
#include 
#include 
#include 

using namespace std;

class BankAccount {
private:
    string accountNumber;
    double balance;

public:
    BankAccount(string accNum, double bal) : accountNumber(accNum), balance(bal) {}

    // Declare external function as friend
    friend void performRegulatoryAudit(const BankAccount &account);
};

// Friend function definition (not a member function)
void performRegulatoryAudit(const BankAccount &account) {
    cout << "[AUDIT REPORT]: Account #" << account.accountNumber 
         << " verified. Balance: ₹" << fixed << setprecision(2) << account.balance << endl;
}

int main() {
    cout << "--- Friend Function Audit ---" << endl;
    BankAccount acc("SBIN99812", 450000.00);
    performRegulatoryAudit(acc); // Directly inspects private members
    return 0;
}
--- Friend Function Audit --- [AUDIT REPORT]: Account #SBIN99812 verified. Balance: ₹450000.00
2. Class-to-Class Friendship (`SmartCar` and `DiagnosticsScanner`)
Declares an entire `DiagnosticsScanner` class as a friend of `SmartCar`, granting it full access to engine telemetry.
C++ / Friend Class Example
#include 
#include 

using namespace std;

class SmartCar {
private:
    string model;
    int engineTempCelsius;
    int fuelLevelPercent;

public:
    SmartCar(string m, int temp, int fuel) : model(m), engineTempCelsius(temp), fuelLevelPercent(fuel) {}

    // Grant friendship to DiagnosticsScanner class
    friend class DiagnosticsScanner;
};

class DiagnosticsScanner {
public:
    void runDiagnosticScan(const SmartCar &car) {
        cout << "--- OBD-II Diagnostic Scan for " << car.model << " ---" << endl;
        cout << "Engine Temperature : " << car.engineTempCelsius << "°C" << endl;
        cout << "Fuel Level         : " << car.fuelLevelPercent << "%" << endl;
    }
};

int main() {
    SmartCar myCar("Tesla Model Y", 92, 78);
    DiagnosticsScanner scanner;
    scanner.runDiagnosticScan(myCar);
    return 0;
}
--- OBD-II Diagnostic Scan for Tesla Model Y --- Engine Temperature : 92°C Fuel Level : 78%
3. Matrix and Vector Multiplication Using Friend Functions
Uses a friend function to perform mathematical matrix-vector multiplication across private matrix elements.
C++ / Friend Matrix Multiplier
#include 

using namespace std;

class Matrix2x2 {
private:
    double m[2][2];

public:
    Matrix2x2(double a, double b, double c, double d) {
        m[0][0] = a; m[0][1] = b;
        m[1][0] = c; m[1][1] = d;
    }

    // Friend function declaration for vector multiplication
    friend void multiplyMatrixVector(const Matrix2x2 &mat, double vec[2], double result[2]);
};

void multiplyMatrixVector(const Matrix2x2 &mat, double vec[2], double result[2]) {
    result[0] = (mat.m[0][0] * vec[0]) + (mat.m[0][1] * vec[1]);
    result[1] = (mat.m[1][0] * vec[0]) + (mat.m[1][1] * vec[1]);
}

int main() {
    cout << "--- Friend Matrix Multiplier ---" << endl;
    Matrix2x2 mat(2.0, 1.0, 1.0, 3.0);
    double vec[2] = {4.0, 5.0};
    double res[2] = {0.0, 0.0};

    multiplyMatrixVector(mat, vec, res);

    cout << "Result Vector: [" << res[0] << ", " << res[1] << "]" << endl;
    return 0;
}
--- Friend Matrix Multiplier --- Result Vector: [13, 19]
4. Cross-Class Coordination: `Player` and `Scoreboard` Friend Function
A specialized friend synchronization function updates game scoreboard statistics using private player scores.
C++ / Cross-Class Friend Coordination
#include 
#include 

using namespace std;

class Player {
private:
    string gamerTag;
    int score;

public:
    Player(string tag, int s) : gamerTag(tag), score(s) {}

    friend void synchronizeLeaderboard(const Player &p1, const Player &p2);
};

void synchronizeLeaderboard(const Player &p1, const Player &p2) {
    cout << "--- Global Leaderboard Synchronization ---" << endl;
    cout << p1.gamerTag << " Score: " << p1.score << endl;
    cout << p2.gamerTag << " Score: " << p2.score << endl;
    
    if (p1.score > p2.score) {
        cout << "Leader: " << p1.gamerTag << endl;
    } else {
        cout << "Leader: " << p2.gamerTag << endl;
    }
}

int main() {
    Player p1("Aarav_Gamer", 2450);
    Player p2("Priya_Pro", 2890);
    synchronizeLeaderboard(p1, p2);
    return 0;
}
--- Global Leaderboard Synchronization --- Aarav_Gamer Score: 2450 Priya_Pro Score: 2890 Leader: Priya_Pro
5. Authentication Token Validator Friend Function
Uses a friend function to inspect private security tokens and validate user authorization levels.
C++ / Friend Token Validator
#include 
#include 

using namespace std;

class SecureSession {
private:
    string username;
    string authToken;

public:
    SecureSession(string uname, string token) : username(uname), authToken(token) {}

    friend bool validateSecurityToken(const SecureSession &session, string inputToken);
};

bool validateSecurityToken(const SecureSession &session, string inputToken) {
    return (session.authToken == inputToken);
}

int main() {
    cout << "--- Token Validator ---" << endl;
    SecureSession session("AaravSharma", "TOKEN_XYZ_99812");

    bool isValid = validateSecurityToken(session, "TOKEN_XYZ_99812");
    cout << "Token Authentication Status: " << (isValid ? "VALID" : "INVALID") << endl;
    return 0;
}
--- Token Validator --- Token Authentication Status: VALID
6. Payroll Tax Calculator Friend Function
A specialized tax calculation friend function accesses private basic salary attributes to compute net deductions.
C++ / Friend Tax Calculator
#include 
#include 
#include 

using namespace std;

class Employee {
private:
    string name;
    double basicSalary;

public:
    Employee(string n, double sal) : name(n), basicSalary(sal) {}

    friend void computeTaxDeduction(const Employee &emp);
};

void computeTaxDeduction(const Employee &emp) {
    double tax = emp.basicSalary * 0.15; // 15% flat tax
    cout << "--- Payroll Tax Assessment ---" << endl;
    cout << "Employee Name  : " << emp.name << endl;
    cout << "Basic Salary   : ₹" << fixed << setprecision(2) << emp.basicSalary << endl;
    cout << "Tax Deduction  : ₹" << tax << endl;
}

int main() {
    Employee emp("Priya Singh", 85000.00);
    computeTaxDeduction(emp);
    return 0;
}
--- Payroll Tax Assessment --- Employee Name : Priya Singh Basic Salary : ₹85000.00 Tax Deduction : ₹12750.00
7. IoT Sensor Calibration Friend Function
A hardware calibration friend routine accesses raw analog register values inside an IoT sensor node.
C++ / Friend Sensor Calibration
#include 
#include 

using namespace std;

class SensorNode {
private:
    int rawAnalogValue;

public:
    SensorNode(int raw) : rawAnalogValue(raw) {}

    friend void calibrateSensorReading(SensorNode &sensor, double calibrationFactor);
};

void calibrateSensorReading(SensorNode &sensor, double calibrationFactor) {
    double calibratedVal = sensor.rawAnalogValue * calibrationFactor;
    cout << "--- Sensor Calibration ---" << endl;
    cout << "Raw Analog Reading     : " << sensor.rawAnalogValue << endl;
    cout << "Calibrated Output Value: " << fixed << setprecision(2) << calibratedVal << endl;
}

int main() {
    SensorNode sensor(512);
    calibrateSensorReading(sensor, 0.0805); // Convert raw ADC to voltage
    return 0;
}
--- Sensor Calibration --- Raw Analog Reading : 512 Calibrated Output Value: 41.22
8. Inventory Stock Reconciler Friend Class
An entire `StockAuditor` class is granted friendship to reconcile warehouse inventory sheets against supplier ledgers.
C++ / Friend Stock Reconciler
#include 
#include 

using namespace std;

class WarehouseInventory {
private:
    string sku;
    int stockCount;

public:
    WarehouseInventory(string itemSku, int count) : sku(itemSku), stockCount(count) {}

    friend class StockAuditor;
};

class StockAuditor {
public:
    void reconcileStock(const WarehouseInventory &inv, int physicalCount) {
        cout << "--- Stock Reconciliation Report ---" << endl;
        cout << "SKU Code        : " << inv.sku << endl;
        cout << "System Records  : " << inv.stockCount << endl;
        cout << "Physical Count  : " << physicalCount << endl;
        
        if (inv.stockCount == physicalCount) {
            cout << "Status          : MATCHED (Zero Variance)" << endl;
        } else {
            cout << "Status          : DISCREPANCY DETECTED" << endl;
        }
    }
};

int main() {
    WarehouseInventory inv("SKU-99812", 150);
    StockAuditor auditor;
    auditor.reconcileStock(inv, 148);
    return 0;
}
--- Stock Reconciliation Report --- SKU Code : SKU-99812 System Records : 150 Physical Count : 148 Status : DISCREPANCY DETECTED
9. Mutual Friendship Between Two Classes
Demonstrates mutual friendship where Class A is a friend of Class B, and Class B is a friend of Class A.
C++ / Mutual Friendship Example
#include 
#include 

using namespace std;

class ClassB; // Forward declaration

class ClassA {
private:
    string secretA = "AlphaSecret99";
public:
    friend class ClassB;
};

class ClassB {
private:
    string secretB = "BetaSecret88";
public:
    friend class ClassA;

    void revealSecrets(const ClassA &a) {
        cout << "ClassB reading ClassA secret: " << a.secretA << endl;
    }
};

int main() {
    cout << "--- Mutual Friendship ---" << endl;
    ClassA a;
    ClassB b;
    b.revealSecrets(a);
    return 0;
}
--- Mutual Friendship --- ClassB reading ClassA secret: AlphaSecret99
10. 2D Point Coordinate Transformer Friend Function
A friend translation function updates X and Y private coordinates of a 2D point object directly.
C++ / Friend Coordinate Transformer
#include 

using namespace std;

class Point2D {
private:
    double x, y;

public:
    Point2D(double px, double py) : x(px), y(py) {}

    friend void translatePoint(Point2D &p, double dx, double dy);

    void display() const {
        cout << "Point Coordinates: (" << x << ", " << y << ")" << endl;
    }
};

void translatePoint(Point2D &p, double dx, double dy) {
    p.x += dx;
    p.y += dy;
}

int main() {
    cout << "--- Coordinate Transformation ---" << endl;
    Point2D pt(10.0, 20.0);
    
    pt.display();
    translatePoint(pt, 5.0, -2.5); // Translates private X and Y directly
    pt.display();
    return 0;
}
--- Coordinate Transformation --- Point Coordinates: (10, 20) Point Coordinates: (15, 17.5)