🤝 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.
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}