A class or a structure may declare any function it’s friend. If a function is a friend of a class, it may access all it’s protected and private members:

If functions or individual classes are used in conjunction with another class, you may
want to grant them access to the private members of that class. This is made possible
by a friend declaration, which eliminates data encapsulation in certain cases.

Imagine you need to write a global function that accesses the elements of a numerical
array class.

If you need to call the access methods of the class each time, and if these methods perform range checking, the function runtime will increase considerably.

However, special permission to access the private data members of the class can dramatically improve the function’s response.

How to use Friend Functions

A class can grant any function a special permit for direct access to its private members.
This is achieved by declaring the function as a friend. The friend keyword must precede the function prototype in the class definition.

class A
{ // . . .
friend void globFunc( A* objPtr);
friend int B::elFunc( const A& objRef);

Here the global function globFunc() and the method elFunc() of class B are
declared as friend functions of class A.

This allows them direct access to the private members of class A. Since these functions are not methods of class A, the this pointer is not available to them. To resolve this issue, you will generally pass the object the function needs to process as an argument.

It is important to note that the class itself determines who its friends are. If this were
not so, data encapsulation could easily be undermined.

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: What is friend function cpp with example

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

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories


Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page


Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
    Strength indicator
    Log In | Lost Password