FRIEND FUNCTIONS IN C++
A friend function is a non-member function that is given special permission to access the private and protected members of a class.
Normally, only member functions
of a class can access private data.
But a friend function breaks this rule safely for special cases.
Syntax
A friend function is declared inside
the class using the keyword friend, but its definition is outside
the class.
class ClassName {
private:
int a;
public:
friend void showData(ClassName obj);
// Declaration
};
Outside class:
void showData(ClassName obj) {
cout << obj.a;
}
Key Properties
|
Property |
Explanation |
|
Not a member |
Friend function is NOT a member
of class. |
|
Can access private/protected |
But it is allowed to access
private and protected data. |
|
Called normally |
It is NOT called using
objectName.function(). |
|
Uses objects as parameters |
It uses object(s) as arguments to
access data. |
|
Can belong to multiple classes |
A single friend function can be
friend of many classes. |
Example
#include <iostream>
using namespace std;
class Sample {
private:
int x;
public:
Sample(int val) { x = val; }
friend void show(Sample s); //
friend declaration
};
void show(Sample s) {
cout << "Value of x = " << s.x; // Accessing private data
}
int main() {
Sample obj(10);
show(obj);
}
Output:
Value of x = 10
Use Cases of Friend
Functions
1. When operator overloading
requires access to private members
2. When two different classes need to share private data
3. When we need non-member functions that still work closely with a class
4. To increase performance
Friend Function vs
Member Function
|
Member Function |
Friend Function |
|
Always belongs to class |
Not part of class |
|
Called using object |
Called normally like a normal
function |
|
Can access private data |
Can access private data |
|
Has this pointer |
No this pointer |
|
Needs object to call |
Needs object only if required as
parameter |
Advantages of Friend Functions
Access private data
Useful for debugging, comparison,
or complex logic.
More flexibility
Can operate across two or more
classes.
Useful in operator overloading
Especially stream operators.
Disadvantages of
Friend Functions
Breaks encapsulation
Allows external functions to access
private data.
Hard to maintain
Excessive use reduces
object-oriented design.
Cannot be inherited
Friendship is not inherited.
0 Comments