Friend Functions
Definition
A friend function is a function declared inside a class using the keyword friend that is allowed to access the private and protected members of that class, even though it is not a member of the class.
A friend function:
- is not called using object syntax
- does not use the
thispointer - can be a normal function, a member of another class, or even a whole class in some cases
- must be declared inside the class definition, but defined outside the class like a normal function
Example idea:
class A {
friend void show(A obj);
private:
int x;
};
Here, show() is not a member of A, but it can access x.
Main Content
1. Need and Purpose of Friend Functions
- Friend functions are used when an external function needs direct access to the internal data of a class without being made a member function.
- They are useful when a function must operate on two or more objects, especially when those objects belong to different classes or when the operation is symmetric, such as adding two complex numbers or comparing two objects.
In object-oriented programming, data members are usually private to protect them from unwanted modification. But sometimes a task cannot be conveniently done by a member function alone. For example, when adding two Complex numbers, the result should be based on both objects. If the function is made a member of one class, it naturally belongs to only that class, but as a friend function, it can work equally with both objects.
Friend functions are also helpful in:
- overloading operators like
<<and>> - writing utility functions for displaying private data
- creating functions that need access to multiple classes’ internals
- improving code readability in certain designs
Example:
#include <iostream>
using namespace std;
class Complex {
int real, imag;
public:
Complex(int r, int i) : real(r), imag(i) {}
friend void addComplex(Complex c1, Complex c2);
};
void addComplex(Complex c1, Complex c2) {
cout << "Sum = " << (c1.real + c2.real) << " + " << (c1.imag + c2.imag) << "i";
}
Here, addComplex() needs access to private members real and imag, so it is declared as a friend.
2. Features and Syntax of Friend Functions
- A friend function is declared inside a class with the keyword
friend, but it is defined outside the class like a normal function. - It is not a member of the class, so it cannot be invoked using an object with the dot operator.
- It can access only those private and protected members of the class that has declared it as a friend.
General syntax:
class ClassName {
friend return_type function_name(parameters);
};
Important characteristics:
- the declaration can appear in any section of the class: private, protected, or public
- friendship is not inherited, meaning a derived class does not automatically get the same friendship
- friendship is not reciprocal; if class A makes function
fa friend, that does not meanfis a friend of every other class - friendship is not transitive; if
fis a friend ofAandAis a friend ofB, that does not makefa friend ofB
Example of syntax:
class Box {
private:
int length;
public:
Box(int l) : length(l) {}
friend void displayLength(Box b);
};
void displayLength(Box b) {
cout << b.length;
}
In this example, displayLength() is declared as a friend and can directly access length.
Friend functions are commonly used with:
- single class access
- multiple class access
- function overloading
- stream operator overloading
3. Applications and Limitations of Friend Functions
- Friend functions are widely used in operator overloading, especially for stream insertion and extraction operators such as
<<and>>. - They are also useful when a function must access private members of multiple classes and when member functions are not the best design choice.
Example: operator overloading with friend function
#include <iostream>
using namespace std;
class Distance {
int feet, inches;
public:
Distance(int f, int i) : feet(f), inches(i) {}
friend ostream& operator<<(ostream& out, const Distance& d);
};
ostream& operator<<(ostream& out, const Distance& d) {
out << d.feet << " feet " << d.inches << " inches";
return out;
}
This is a very common use because the left side of << is cout, which is not an object of the class, so a member function cannot be used conveniently.
Limitations of friend functions:
- they break encapsulation to some extent because they can access private data directly
- too many friend functions can make class design less secure
- they are not inherited by derived classes
- they are not members of the class, so they cannot access
thisor call member functions directly unless an object is passed
Despite these limitations, friend functions are valuable when used carefully and only where needed. Good programming practice recommends using them sparingly, only when there is a clear benefit.
Working / Process
1. Declare the function as a friend inside the class
- The class author identifies which external function needs special access.
- The function prototype is written inside the class with the
friendkeyword.
2. Define the function outside the class
- The friend function is written like a normal non-member function.
- No scope resolution with the class name is used during declaration, but it can access private and protected members through class objects passed as arguments.
3. Use object(s) of the class inside the function
- The function receives one or more objects as parameters.
- It accesses their private members directly and performs the required operation.
Example:
#include <iostream>
using namespace std;
class Sample {
int a;
public:
Sample(int x) : a(x) {}
friend void printValue(Sample s);
};
void printValue(Sample s) {
cout << "Value = " << s.a;
}
int main() {
Sample obj(25);
printValue(obj);
}
Working explanation:
printValue()is declared as a friend inSample- it is defined outside the class
- it takes an object
sas parameter - it accesses
s.adirectly even thoughais private - the function is called like a normal function, not through an object
Advantages / Applications
- Friend functions provide controlled access to private and protected data when needed.
- They are very useful in operator overloading, especially for binary operators and stream operators.
- They simplify tasks involving two or more classes or two objects of the same class.
- They improve flexibility in cases where member functions are not suitable.
- They are applied in utility functions, debugging functions, mathematical operations, and input/output handling.
Common applications include:
- addition/subtraction of objects
- comparison of objects
- overloaded
<<and>>operators - cross-class data access
- functions that need direct but limited access to class internals
Summary
- Friend functions are non-member functions that can access private and protected data of a class.
- They are declared inside the class using the
friendkeyword and defined outside the class. - They are mainly used when an external function needs special access, especially in operator overloading and multi-object operations.
- Important terms to remember: friend function, encapsulation, access specifier, operator overloading, non-member function