Skip to content

Friend Class / Function

A friend is a special permission given to a function or class to access private and protected members of another class — even though it's not a member of that class.

Think: like giving a spare key to your house to a trusted friend — they can access things others can't.

Friend Function

cpp
class Box {
private:
    int length = 10, width = 5, height = 3;
    friend int volume(Box); // declare friend function
};

int volume(Box b) { // defined outside — NOT a member
    return b.length * b.width * b.height; // direct private access
}

int main() {
    Box b;
    cout << volume(b) << endl; // 150
}

Friend Class

cpp
class Engine {
private:
    int horsepower = 500, torque = 400;
    friend class Car; // Car can access Engine's private members
};

class Car {
public:
    void showSpecs(Engine e) {
        cout << "HP: " << e.horsepower << endl;   // direct access
        cout << "Torque: " << e.torque << endl;
    }
};

Friend Function of Another Class

cpp
class ClassB; // forward declaration needed!

class ClassA {
private:
    int dataA = 100;
    friend void share(ClassA, ClassB); // friend function
};

class ClassB {
private:
    int dataB = 200;
    friend void share(ClassA, ClassB); // friend function
};

void share(ClassA a, ClassB b) { // can access private of BOTH
    cout << a.dataA << endl; // 100
    cout << b.dataB << endl; // 200
}

Friend Is NOT Mutual — Important Rules!

cpp
// Rule 1 — friendship is NOT mutual
// if A is friend of B, B is NOT friend of A

// Rule 2 — friendship is NOT inherited
class A { friend class B; };
class C : public B {}; // C is NOT a friend of A

// Rule 3 — friendship is NOT transitive
// if A is friend of B, and B is friend of C
// A is NOT a friend of C

// Rule 4 — friend declaration can be in private section too

Friend with Operator Overloading — Very Common!

cpp
class Vector {
private:
    float x, y;
public:
    Vector(float x, float y) : x(x), y(y) {}

    friend ostream& operator<<(ostream& out, const Vector& v) {
        out << "(" << v.x << ", " << v.y << ")";
        return out;
    }

    friend Vector operator+(const Vector& a, const Vector& b) {
        return Vector(a.x + b.x, a.y + b.y);
    }
};

Vector v3 = v1 + v2;
cout << v3 << endl; // (4, 6)

operator<< and operator+ need private access — friend is perfect here.

When to Use Friend

  • Good uses: Operator overloading (<<, >>, +, -), two tightly coupled classes, testing, factory pattern
  • Bad uses: Just to avoid writing getters/setters, overusing it, between unrelated classes

Summary Table

Friend FunctionFriend Class
Declared withfriend keywordfriend keyword
DefinedOutside classSeparately
Is a member?NoNo
Mutual?NoNo
Inherited?NoNo
Transitive?NoNo

One-liner: "A friend function or class is granted special access to private and protected members of a class — friendship is not mutual, not inherited, and not transitive."