C++ Friend Functions Explained

In C++, a friend function is a non-member function that can access a class’s private and protected members. Friend functions can be declared inside a class but must be defined outside of it. They can access the private and protected members of a class but not its member functions.

Friend functions are typically used to overload operators and other functions in order to access a class’s private and protected members, but they are not member functions of the class. The usage of friend functions can simplify code logic and make operator overloading more flexible and convenient.

For example, here is a simple demonstration showing how to use friend functions in C++.

#include <iostream>

class Test {
private:
    int x;

public:
    Test(int x) : x(x) {}

    friend void display(Test t);
};

void display(Test t) {
    std::cout << "The value of x is: " << t.x << std::endl;
}

int main() {
    Test t(10);
    display(t);

    return 0;
}

In this example, we define a class Test containing a private member x. Then we declare a friend function display that can access the private member x of the Test class. In the main function, we create a Test object t and call the friend function display to output the value of the private member x of object t.

Friend functions can offer more flexibility and scalability in the design of a class, but they should be used cautiously as they compromise encapsulation.

bannerAds