Friend functions are a unique feature of C++ that allow functions to access private and protected data of a class. A friend function is a non-member function that is given access to the private and protected members of a class.
Declaring a Friend Function
To declare a friend function, the friend
keyword must be used before the function prototype in the class declaration. Here’s an example:
class MyClass {
private:
int privateVar;
public:
friend void friendFunction(MyClass& obj);
};
C++In this example, friendFunction
is declared as a friend function of the MyClass
class. This means that friendFunction
can access the private members of MyClass
.
Defining a Friend Function
To define a friend function, the friend
keyword is not used. Instead, the function is defined like any other function outside the class definition. However, the function parameter list must include a reference to the class object that it is a friend of.
void friendFunction(MyClass& obj) {
obj.privateVar = 10;
}
C++In this example, friendFunction
sets the private variable privateVar
of MyClass
to 10.
Using Friend Functions
Once a friend function is declared in a class, it can be used like any other function. Here’s an example:
MyClass obj;
friendFunction(obj);
C++In this example, friendFunction
is called with an instance of MyClass
as a parameter.
Benefits of Friend Functions
Friend functions can be useful in situations where a function needs to access private or protected data of a class, but it does not make sense for that function to be a member function of the class. Friend functions can also be used to improve code readability and organization.
Drawbacks of Friend Functions
However, using friend functions can also make code more difficult to maintain and test. It can also increase the risk of accidental misuse of private data by making it more widely accessible.
Conclusion
Friend functions are a powerful feature of C++ that allow non-member functions to access private and protected members of a class. They can be useful in certain situations, but should be used with caution to avoid potential drawbacks.