What are Friend Functions and Friend Classes in C++ ?
![]() Don't want to miss a single bit? Subscribe By Email for Daily Jobs |
A friend can be a function, another class or individual member function of a class. With the help of a friend function it is possible to grant a non member function access to the private members of a class using a friend.
A friend function has all access to all the private and protected members of the class for which it is the friend. To declare a friend function includes the function prototype within the class preceding it with the keyword friend. When a friend function is called it need to be qualified by the object name as it is not a member function of the class. E.g.
class Complex
{
private:
float real;
float imaginary;
public:
friend Complex operator+ (Complex, Complex);
};
//overloaded + operator for class Complex
Complex operator+ (Complex c, Complex d)
{
Complex tmp;
tmp.real = d.real + c.real;
tmp.imaginary = d.imaginary + c.imaginary;
return temp;
}
To call the function:
int main ()
{
Complex a, b, c;
a = b + c; //this will be called as operator+(b, c)
}
Friend classes are used when two or more classes are designed to work together and need access to each other’s implementation. E.g. a class DataBaseCursor may want more privileges to the class Database. E.g.
class DatabaseCursor;
class Database
{
//member variable and function declarations
friend DatabaseCursor;
};
Related Articles
- What is Operator Overloading in C++ ?
- What is ‘this’ Pointer (object) in C++
- What are Virtual Functions ? Why do we need Virtual Functions? Explain with an example.
- What are static Data and Static Member Functions in C++ ?
- What is a Pure Virtual Member Function ?


