BCA / B.Tech 10 min read

Friend Function in C++

Friend Function in C++:


In C++, a friend function is a feature that plays an important role in programming, especially when we want to access the private and protected data of a class while following the principle of data security (Encapsulation). Using a friend function, we can grant an external function or class permission to access the private and protected data of another class.

What is a Friend Function?
A friend function in C++ is a function that is declared inside a class with the `friend` keyword. This function is not part of that class, but it is allowed to access the private and protected data of that class.

Key Features of a Friend Function:
Not a member function, defined outside the class, can be a friend to any class, and is not called through an object of the class.

Need for a Friend Function:
Needed for data security when external functions need access, for data access between multiple classes, and often for operator overloading.

Advantages of a Friend Function:
Access to private data, external implementation, useful for operator overloading, and can access data from multiple classes.

Disadvantages of a Friend Function:
Reduces data security by violating encapsulation, can increase code complexity, and is not a member function so it cannot be called using an object.

Friend Class:
A class can also be declared as a friend, which means it can access all the private and protected members of the class that befriended it.