In C++, if a function is declared as a buddy function, the function can access a class’s protected and private data.
The keyword friend informs the compiler that the given function is a friend function.
A class’s friend function is defined outside of the scope of the class, yet it has access to all private and protected elements of the class. Friends are not member functions, despite the fact that prototypes for friend functions appear in the class specification.
A function, function template, or member function can be a friend, as can a class or class template, in which case the entire class and its members are friends.
For accessing data, a friend function should be declared inside the body of a class, beginning with the term friend.
Declaration of Friend Functions
class class_name
{
friend data_type function_name(argument); // syntax of friend function.
};
The friend function prefixes the term friend in the above declaration. Like any other C++ function, the function can be defined anywhere in the program. Neither the keyword friend nor the scope resolution operator are used in the function declaration.
Characteristics
- The method isn’t in the scope of the class it’s a buddy for.
- Secondly, It can’t be called with the object because it’s not in that class’s scope.
- It can be called just like any other function without requiring an object.
- Next, It can’t directly access member names, thus it must use an object name and the dot membership operator with the member name.
- It can write in a private or public area.
Some important points
Here are some key points to remember regarding friend functions and classes:
1) Friends should only be utilized for specific purposes. When too many functions or external classes are defined as friends of a class with protected or private data, the usefulness of object-oriented programming’s encapsulation of separate classes is diminished.
2) Friendship is not a two-way street. If class A is a friend of class B, B does not immediately become a friend of A.
3) Friendship is not something you inherit.
4) In Java, the concept of friends does not exist.
Interested in learning about similar topics? Here are a few hand-picked blogs for you!
- What is recursion?
- Describe compiler?
- What is programming?
- Explain constructor?
- What is object-oriented programming?