Please provide sample code of Friend Function in C++.
Please provide sample code of Friend Function in C++.
21407-Sep-2023
Updated on 25-Sep-2023
Home / DeveloperSection / Forums / Please provide sample code of Friend Function in C++.
Please provide sample code of Friend Function in C++.
Aryan Kumar
25-Sep-2023In C++, friend functions are functions that are not members of a class but are granted access to the private and protected members of that class. They can be useful in scenarios where you need to allow external functions or classes to manipulate or access the private data of a class. Here's a sample code that demonstrates how to declare and use a friend function in C++:
In this example:
Please note that while friend functions can be useful in certain situations, they should be used sparingly, as they can break encapsulation and make the code less maintainable if overused. It's generally recommended to prefer member functions and accessor methods (getters and setters) for interacting with the private data of a class when possible.