Loading lessons...
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::).
class ABC {
// ...
public:
friend void xyz(ABC& obj); // declaration inside the class
};
void xyz(ABC& obj) { // definition: an ordinary function
// ...
}Characteristics
- It is not in the scope of the class, so it is not called with an object: write
xyz(a), nota.xyz(). - 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. - It can be declared in the
privateor thepublicpart of the class; the access specifier makes no difference. - It is invoked like a normal function, without an object.
- It has no
thispointer. - A function can be a friend of any number of classes.
#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:
Mean value = 32.52. 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.
#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:
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.
#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:
Before exchange: 100
200
After exchange: 200
100- 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:
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.
#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:
Engine power: 150 hp
Engine power: 180 hpProperties of friendship
| Property | Meaning |
|---|---|
| Granted, not taken | a class decides who its friends are; a function cannot declare itself a friend |
| Not mutual | if Car is a friend of Engine, Engine is not automatically a friend of Car |
| Not transitive | a friend of a friend is not a friend |
| Not inherited | a class derived from Car is not a friend of Engine |
5. Member Function vs Friend Function
| Member function | Friend function |
|---|---|
| defined in the scope of the class | not in the scope of the class |
called with an object: x.show() | called like a normal function: show(x) |
| accesses members directly by name | accesses members through an object: x.a |
has a this pointer | has no this pointer |
| belongs to one class | can be a friend of several classes |
affected by public / private placement | placement under an access specifier does not matter |
| inherited by derived classes | not 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 << objor2 * obj(Lesson 20). - It can make some code clearer, e.g.
distance(p, q)instead ofp.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.
Key points to remember
- A friend function is a non-member with access to private members; declared with
friendinside 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.
📝 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/Betaprogram 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)