Friend Functions & Classes

Friend functions are those that, despite not being declared inside the class, have permission to access the private information of its members. The friend function prototype needs to be written.

A function is not a member of a class just because it is declared as a buddy function inside the class.

Properties of Friend Function

  • It is not a member of the class if it is not inside the scope of the class.
  • It cannot be invoked from the class’s object because it is outside of its scope.
  • It doesn’t matter where in the class it is declared, or whether it is under the public or private access modifier.
  • It needs (object name.member name) to access any member because it cannot access the members directly by name.

Declaring a friend function inside a class requires the following syntax.

class class_name
    friend return_type function_name(arguments);
return_type class_name::function_name(arguments)
    //body of the function

Friend Classes in C++

Classes that are declared as friends have access to the private members of the class in which they are used. The most important point to keep in mind is that once a class becomes friends with another class, it has access to all of its private members.

The syntax for a friend class declaration within a class is

class class_name
    friend class friend_class_name;
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.