🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Friend Functions & Classes

C++ Friend Functions and Friend Classes

Friend Functions in C++

Friend functions are those functions that have the right to access the private data of members of the class even though they are not defined inside the class. It is necessary to write the prototype of the friend function.

Declaring a friend function inside a class does not make that function a member of the class.

Properties of Friend Function

  • Not in the scope of the class, means it is not a member of the class.
  • Since it is not in the scope of the class, it cannot be called from the object of that class.
  • Can be declared anywhere inside the class, be it under the public or private access modifier, it will not make any difference.
  • It cannot access the members directly by their names; it needs (object_name.member_name) to access any member.

Syntax for Declaring a Friend Function Inside a Class


class class_name
{
    friend return_type function_name(arguments);
};

return_type class_name::function_name(arguments)
{
    //body of the function
}

Friend Classes in C++

Friend classes are those classes that have permission to access private members of the class in which they are declared. The main thing to note here is that if the class is made friends of another class then it can access all the private members of that class.

Syntax for Declaring a Friend Class Inside a Class


class class_name
{
    friend class friend_class_name;
};

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.