What is Friend Function in C++

Data hiding is a fundamental concept of object-oriented programming. It restricts the access of private members from outside of the class. Similarly, protected members can only be accessed by derived classes and are inaccessible from outside. 

However, there is a feature in C++ called friend functions that break this rule and allows us to access member functions from outside the class. 

Friend Function

  • A friend function can access the private and protected data of a class. 
  • We declare a friend function using the friend keyword inside the body of the class.

Syntax

class className {
    friend returnType functionName(arguments);
}
  • The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition.
  • When the friend function is called neither the name of the object nor the dot operator is used. However, it may accept the object as an argument whose value it wants to access.

Example

#include <iostream>
using namespace std;

class MyClass {
private:
    int a = 111;
    friend void display(MyClass obj);
};

void display(MyClass obj) {
    cout << obj.a;
}

int main() {
    MyClass obj;
    display(obj);
    return 0;
}

Conclusion 

Friend functions in C++ enable access to private and protected class members from outside the class, bypassing encapsulation. Despite breaking the conventional data-hiding principle, they offer a targeted approach for specific functions to interact with class internals. While their usage should be judicious to maintain code integrity, they provide a powerful tool for enhancing flexibility in C++ programming.


Similar Articles