Lesson 12 +30 XP

Friend Functions & Friend Classes

Friend Functions & Friend Classes

The private members of a class can normally be reached only by that class's own member functions. Sometimes, though, a function needs to work with the private data of two different classes at once, such as a function comparing a Manager with a Scientist. C++ allows a class to grant such access to a chosen outside function by declaring it a friend.

1. Friend Functions

A friend function is a non-member function that is given access to the private and protected members of a class. It is declared inside the class with the keyword friend, and defined outside like an ordinary function (without friend and without ClassName::).

C++
class ABC {
    // ...
public:
    friend void xyz(ABC& obj); // declaration inside the class
};
void xyz(ABC& obj) { // definition: an ordinary function
    // ...
}

Characteristics

  1. It is not in the scope of the class, so it is not called with an object: write xyz(a), not a.xyz().
  2. It cannot access members directly by name: it must use an object and the dot operator, such as obj.x. So it usually takes an object as an argument.
  3. It can be declared in the private or the public part of the class; the access specifier makes no difference.
  4. It is invoked like a normal function, without an object.
  5. It has no this pointer.
  6. A function can be a friend of any number of classes.
C++
#include <iostream>
using namespace std;

class Sample {
    int a, b;

public:
    void setValue() {
        a = 25;
        b = 40;
    }
    friend float mean(Sample s); // friend declaration
};

float mean(Sample s) {           // not a member: no Sample::
    return float(s.a + s.b) / 2; // private members through the object
}

int main() {
    Sample x;
    x.setValue();
    cout << "Mean value = " << mean(x) << endl; // called like a normal function
    return 0;
}

Output:

OUTPUT
Mean value = 32.5

2. A Friend of Two Classes

This is the main reason friends exist. A function needs private data from two classes, so it is made a friend of both. Because each class mentions the other before it is fully defined, a forward declaration class B; is needed.

C++
#include <iostream>
using namespace std;

class Beta; // forward declaration

class Alpha {
    int value;

public:
    Alpha(int v) {
        value = v;
    }
    friend void maxOf(Alpha a, Beta b);
};

class Beta {
    int value;

public:
    Beta(int v) {
        value = v;
    }
    friend void maxOf(Alpha a, Beta b);
};

void maxOf(Alpha a, Beta b) { // reads private data of both classes
    if (a.value >= b.value) {
        cout << "Max is " << a.value << " (from Alpha)" << endl;
    } else {
        cout << "Max is " << b.value << " (from Beta)" << endl;
    }
}

int main() {
    Alpha a(30);
    Beta b(45);
    maxOf(a, b);
    return 0;
}

Output:

OUTPUT
Max is 45 (from Beta)

Swapping private data of two classes (call by reference)

A friend function can also modify private data if the objects are passed by reference.

C++
#include <iostream>
using namespace std;

class Class2;

class Class1 {
    int value1;

public:
    void indata(int a) {
        value1 = a;
    }
    void display() {
        cout << value1 << endl;
    }
    friend void exchange(Class1& x, Class2& y);
};

class Class2 {
    int value2;

public:
    void indata(int a) {
        value2 = a;
    }
    void display() {
        cout << value2 << endl;
    }
    friend void exchange(Class1& x, Class2& y);
};

void exchange(Class1& x, Class2& y) {
    int temp = x.value1;
    x.value1 = y.value2;
    y.value2 = temp;
}

int main() {
    Class1 c1;
    Class2 c2;
    c1.indata(100);
    c2.indata(200);
    cout << "Before exchange: ";
    c1.display();
    cout << "                 ";
    c2.display();
    exchange(c1, c2);
    cout << "After exchange:  ";
    c1.display();
    cout << "                 ";
    c2.display();
    return 0;
}

Output:

OUTPUT
Before exchange: 100
                 200
After exchange:  200
                 100
  1. A Member Function of One Class as a Friend of Another

Instead of a free function, a member function of another class can be made a friend:

C++
class X {
public:
    int fun1(); // member function of X
};
class Y {
    friend int X::fun1(); // only X::fun1 may access Y's private members
};

4. Friend Classes

If all member functions of class X need access to class Y's private members, X can be made a friend class of Y.

C++
#include <iostream>
using namespace std;

class Engine {
    int horsepower;
    friend class Car; // every member of Car may access Engine's privates
public:
    Engine() {
        horsepower = 150;
    }
};

class Car {
    Engine e;

public:
    void tune(int extra) {
        e.horsepower = e.horsepower + extra;
    }
    void show() {
        cout << "Engine power: " << e.horsepower << " hp" << endl;
    }
};

int main() {
    Car c;
    c.show();
    c.tune(30);
    c.show();
    return 0;
}

Output:

OUTPUT
Engine power: 150 hp
Engine power: 180 hp

Properties of friendship

PropertyMeaning
Granted, not takena class decides who its friends are; a function cannot declare itself a friend
Not mutualif Car is a friend of Engine, Engine is not automatically a friend of Car
Not transitivea friend of a friend is not a friend
Not inheriteda class derived from Car is not a friend of Engine

5. Member Function vs Friend Function

Member functionFriend function
defined in the scope of the classnot in the scope of the class
called with an object: x.show()called like a normal function: show(x)
accesses members directly by nameaccesses members through an object: x.a
has a this pointerhas no this pointer
belongs to one classcan be a friend of several classes
affected by public / private placementplacement under an access specifier does not matter
inherited by derived classesnot inherited

6. Merits and Demerits

Merits:

  • A single function can operate on objects of two or more classes.
  • It allows operator overloading where the left operand is not an object of the class, such as cout << obj or 2 * obj (Lesson 20).
  • It can make some code clearer, e.g. distance(p, q) instead of p.distance(q).

Demerits:

  • It breaks data hiding and encapsulation: private data is open to an outside function.
  • Overuse makes the program harder to maintain, since changes to private data now affect non-members too.
  • Friend functions cannot be inherited or made virtual.
💡 Tip

Key points to remember

  • A friend function is a non-member with access to private members; declared with friend inside the class.
  • It is called without an object and reaches members through an object argument (s.a).
  • Use it for functions needing private data of two classes (forward-declare the second class).
  • A friend class gives all its members access. Friendship is not mutual, not transitive, not inherited.
  • It weakens encapsulation, so use it sparingly.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is a friend function? State its characteristics. Write a program to find the larger of two private numbers belonging to two different classes using a friend function. (10 Marks)
  • Write: the definition, the six characteristics, and the Alpha/Beta program with output.
  • Q2. Write a program to swap the private data of two classes using a friend function. (5 Marks)
  • Q3. What is a friend class? Is friendship mutual or inherited? (2.5 Marks)
  • Q4. Differentiate between a member function and a friend function. (5 Marks)
  • Q5. "Friend functions violate data hiding." Comment. (2.5 Marks)