8.13 — Friend functions and classes

For much of this chapter, we’ve been preaching the virtues of keeping your data private. However, you may occasionally find situations where you will find you have classes and functions outside of those classes that need to work very closely together. For example, you might have a class that stores data, and a function (or another class) that displays the data on the screen. Although the storage class and display code have been separated for easier maintenance, the display code is really intimately tied to the details of the storage class. Consequently, there isn’t much to gain by hiding the storage classes details from the display code.

In situations like this, there are two options:
1) Have the display code use the publicly exposed functions of the storage class. However, this has several potential downsides. First, these public member functions have to be defined, which takes time, and can clutter up the interface of the storage class. Second, the storage class may have to expose functions for the display code that it doesn’t really want accessible to anybody else. There is no way to say “this function is meant to be used by the display class only”.

2) Alternatively, using friend classes and friend functions, you can give your display code access to the private details of the storage class. This lets the display code directly access all the private members and functions of the storage class, while keeping everyone else out! In this lesson, we’ll take a closer look at how this is done.

Friend functions

A friend function is a function that can access the private members of a class as though it were a member of that class. In all other regards, the friend function is just like a normal function. A friend function may be either a normal function, or a member function of another class. To declare a friend function, simply use the friend keyword in front of the prototype of the function you wish to be a friend of the class. It does not matter whether you declare the friend function in the private or public section of the class.

Here’s an example of using a friend function:

In this example, we’ve declared a function named reset() that takes an object of class Accumulator, and sets the value of m_value to 0. Because reset() is not a member of the Accumulator class, normally reset() would not be able to access the private members of Accumulator. However, because Accumulator has specifically declared this reset() function to be a friend of the class, the reset() function is given access to the private members of Accumulator.

Note that we have to pass an Accumulator object to reset(). This is because reset() is not a member function. It does not have a *this pointer, nor does it have an Accumulator object to work with, unless given one.

Here’s another example:

In this example, we declare the isEqual() function to be a friend of the Value class. isEqual() takes two Value objects as parameters. Because isEqual() is a friend of the Value class, it can access the private members of all Value objects. In this case, it uses that access to do a comparison on the two objects, and returns true if they are equal.

While both of the above examples are fairly contrived, the latter example is very similar to cases we’ll encounter in chapter 9 when we discuss operator overloading!

Multiple friends

A function can be a friend of more than one class at the same time. For example, consider the following example:

There are two things worth noting about this example. First, because PrintWeather is a friend of both classes, it can access the private data from objects of both classes. Second, note the following line at the top of the example:

This is a class prototype that tells the compiler that we are going to define a class called Humidity in the future. Without this line, the compiler would tell us it doesn’t know what a Humidity is when parsing the prototype for PrintWeather() inside the Temperature class. Class prototypes serve the same role as function prototypes -- they tell the compiler what something looks like so it can be used now and defined later. However, unlike functions, classes have no return types or parameters, so class prototypes are always simply class ClassName, where ClassName is the name of the class.

Friend classes

It is also possible to make an entire class a friend of another class. This gives all of the members of the friend class access to the private members of the other class. Here is an example:

Because the Display class is a friend of Storage, any of Display’s members that use a Storage class object can access the private members of Storage directly. This program produces the following result:

6.7 5

A few additional notes on friend classes. First, even though Display is a friend of Storage, Display has no direct access to the *this pointer of Storage objects. Second, just because Display is a friend of Storage, that does not mean Storage is also a friend of Display. If you want two classes to be friends of each other, both must declare the other as a friend. Finally, if class A is a friend of B, and B is a friend of C, that does not mean A is a friend of C.

Be careful when using friend functions and classes, because it allows the friend function or class to violate encapsulation. If the details of the class change, the details of the friend will also be forced to change. Consequently, limit your use of friend functions and classes to a minimum.

Friend member functions

Instead of making an entire class a friend, you can make a single member function a friend. This is done similarly to making a normal function a friend, except using the name of the member function with the className:: prefix included (e.g. Display::displayItem).

However, in actuality, this can be a little trickier than expected. Let’s convert the previous example to make Display::displayItem a friend member function. You might try something like this:

However, it turns out this won’t work. In order to make a member function a friend, the compiler has to have seen the full definition for the class of the friend member function (not just a forward declaration). Since class Storage hasn’t seen the full definition for class Display yet, the compiler will error at the point where we try to make the member function a friend.

Fortunately, this is easily resolved simply by moving the definition of class Display before the definition of class Storage.

However, we now have another problem. Because member function Display::displayItem() uses Storage as a reference parameter, and we just moved the definition of Storage below the definition of Display, the compiler will complain it doesn’t know what a Storage is. We can’t fix this one by rearranging the definition order, because then we’ll undo our previous fix.

Fortunately, this is also fixable in a couple of simple steps. First, we can add class Storage as a forward declaration. Second, we can move the definition of Display::displayItem() out of the class, after the full definition of Storage class.

Here’s what this looks like:

Now everything will compile properly: the forward declaration of class Storage is enough to satisfy the declaration of Display::displayItem() inside the Display class, and the full definition of class Storage is enough to satisfy the definition of Display::displayItem().

If this seems like a pain -- it is. Fortunately, this dance is only necessary because we’re trying to do everything in a single file. A better solution is to put each class definition in a separate header file, with the member function definitions in corresponding .cpp files. That way, all of the class definitions would have been visible immediately in the .cpp files, and no rearranging of classes or functions is necessary!


A friend function or class is a function or class that can access the private members of another class as though it were a member of that class. This allows the friend or class to work intimately with the other class, without making the other class expose its private members (e.g. via access functions).

Friending is uncommonly used when two or more classes need to work together in an intimate way, or much more commonly, when defining overloading operators (which we’ll cover in chapter 9).

Note that making a class a friend only requires a forward declaration for the class. However, making a specific member function a friend requires the full definition for the class of the member function to have been seen first.

Quiz time

1) In geometry, a point is a position in space. We can define a point in 3d-space as the set of coordinates x, y, and z. For example, the Point(2.0, 1.0, 0.0) would be the point at coordinate space x=2.0, y=1.0, and z=0.0.

In physics, a vector is a quantity that has a magnitude (length) and a direction (but no position). We can define a vector in 3d-space as an x, y, and z value representing the direction of the vector along the x, y, and z axis (the length can be derived from these). For example, the Vector(2.0, 0.0, 0.0) would be a vector representing a direction along the positive x-axis (only), with length 2.0.

A Vector can be applied to a Point to move the Point to a new position. This is done by adding the vector’s direction to the point’s position to yield a new position. For example, Point(2.0, 1.0, 0.0) + Vector(2.0, 0.0, 0.0) would yield the point (4.0, 1.0, 0.0).

Points and Vectors are often used in computer graphics (the point to represent vertices of shape, and vectors represent movement of the shape).

Given the following program:

1a) Make Point3d a friend class of Vector3d, and implement function Point3d::moveByVector()

Show Solution

1b) Instead of making class Point3d a friend of class Vector3d, make member function Point3d::moveByVector a friend of class Vector3d.

Show Solution

1c) Reimplement the solution to quiz question 1b using 5 separate files: Point3d.h, Point3d.cpp, Vector3d.h, Vector3d.cpp, and main.cpp.

Thanks to reader Shiva for the suggestion and solution.

Show Solution

8.14 -- Anonymous objects
8.12 -- Static member functions

158 comments to 8.13 — Friend functions and classes

  • SJ

    Hi Alex,

    First of all great lesson! A lot of information here to absorb but I think I have the idea of friend functions down.

    I tried to implement the quiz by using separate .h and .cpp files for the class declarations and member function definitions, but I ran into a small error. I am getting the error that

    " ‘Point3d’ has not been declared "

    in one of my files, even though I included the necessary header. Below are the files and their contents:






    and am receiving the error on the line

    in Vector3d.h

    Can you spot the issue? :\

    • Alex

      Without compiling this to see where the actual error is, I do note that Point3d.h calls Vector3d.h, and Vector3d.h calls Point3d.h. That circular dependency will end in tears, since the header guards will guarantee that one of the headers won’t get the information it needs. Try replacing one of the #includes with a class forward declaration (I think you can forward declare class Vector3d in Point3d.h instead of #including Vector3d.h).

      • SJ

        That was it! Seems so trivial now that you mentioned it. I guess that’s part of the learning process 🙂

        I also forgot to #include <iostream>. Whoops.

  • Gemparks

    Do you mind clarify a bit further on this sentence: "This is because reset() is not a member function. It does not have a *this pointer"?

    From what i understand, it means that you can’t any assignment on any class member the friend function or class is "befriended with", because it can’t "hold the address of the object the member function was called on"..

    But then, i notice that you can do class member assignment via friend function such as this

    I may have misunderstand the whole thing, therefore what does the aforementioned sentence actually imply?
    This chapter kinda throws me off balance a bit
    Great tutorial though, as always.

    Thanks in advance

    • Alex

      Member functions have an implicit *this pointer that point at the class object that the function can operate on. Non-member functions do not. Full stop.

      Friend functions are given privileges to access or modify the internals (private members) of objects of the friending class, as if they were part of the class. Full stop.

      So in the case of the reset() example, this function is able to access the internals of Accumulator because it is a friend of class Accumulator -- however, because it is a non-member friend, it does not have a *this of type Accumulator to work on. Instead, we’re passing in an Accumulator parameter, and it can work on that (using its friend privileges to set m_value directly).

  • hey , sorry but I forgot in which lesson you told as about the compiler adding *this pointer in the member functions , can u remind me of the lesson please ?

  • Xhevo

    Hi, Alex

    Typo to line 11 of friend member functions:

    11. void Display::displayItem(Storage &storage);// forward declaration above needed for this declaration line

    should be:
    11. void displayItem(Storage &storage); // forward declaration above needed for this declaration line
                                                                                                 Thanks again!

  • Bryan

    Thanks for the tutorial.
    I have a question, how to do when Storage and Display classes are in separate files(Storage.h, Storage.cpp, Display.h, Display.cpp)? The compiler shows error: invalid use of incomplete type ‘class Storage’

  • malt

    On the solution for the 1b) i got this error:
    main.cpp 22:7: error: extra qualification ‘Point3d::’ on member ‘moveByVector’ [-fpermissive]
      void Point3d::moveByVector(Vector3d &v); // so we can use Vector3d here

    I use g++ -std=c++11 main.cpp for compile.

    • Alex

      Oops, my bad. I accidentally left a Point3d:: prefix on moveByVector. Visual Studio didn’t complain about it, so I didn’t notice. The example is fixed now.

  • Meric

    Hmmm. The compiler (g++ with -std=c++0x) kept complaining until I made the following changes to the code given under "Multiple Friends". Any idea why?

  • Lokesh

    Quiz 1a. solution - line 20

    should be

  • Lokesh

    In first code example in this lesson,

    should be

  • Lokesh

    In the "multiple friends" section the setHumidity() and setTemperature() functions used in main() are not defined inside the class definitions.

  • JonM

    First I want to thank you on a fantastic tutorial.

    Instead of using Friend class, could one not just get the same result, with just accessing the friend class through getters and setters? And no risk of violating encapsulation would be at risk?

  • Reaversword

    I’ve been trying to get reciprocal "friendship" between two classes. I don’t know if this is nonsense, is just for make the try. But I’m unable to get it working. The only way to get one single class being friend of another one is with this "order":

    1)forward declaration of the friend class (the one able to access the other one’s data)
    2)definition of the class gonna be accessed (the one which accepts friendship)
    3)definition of the friend class.

    If I go out of that structure, it doesn’t works (as swap 2 & 3 steps).

    This is the rule for friendship between classes?.

    A quick example:

    VisualStudio throws the error:

    C2027    use of undefined type ‘Bclass’
    C2228    left of ‘.bVar’ must have class/struct/union

    So, what’s wrong?
    There is a way to get both classes friend of each other?

    • Alex

      The problem here is that the forward declaration tells the compiler about the existence of a class, but nothing about it’s details. So the compiler can’t validate what members the class has.

      The best way to solve this is to move the function definitions out of the class declarations. That way, by the time the compiler compiles them, it will have already seen the class declarations and should know how to resolve all of the names.

      • Reaversword

        Now I understand. Wow!, I was trusting too much in the forward declaration sentence. I really didn’t expect that. Thank you Alex, one more time, brilliant explanation, consecuent solution.

        I leave the code, if somebody wants take a look:

  • Mr D

    Hi Alex,

    Regarding the first code example from this lesson:

    If i understand correctly, the reason you’re using a reference (Accumulator &cAccumulator for example) is because there’s also an int main() part that’s implicit, but that you didn’t write out?
    So for example, the whole thing might look something like this?!:

    • Alex

      No, reset is passed in as a reference so that the function can modify the actual Accumulator argument passed in, not a copy of it. If you were to pass cAccumulator by value, you’d end up resetting a copy of the argument, and the original argument would be unchanged. That would defeat the purpose of calling the function. 🙂

      • Danny

        I have read in one of your tutorials that passing by reference saves the overhead that would rather be incurred when passing by value.
        I tried the same program example with passing by value and it works perfectly fine.

        • Alex

          > I have read in one of your tutorials that passing by reference saves the overhead that would rather be incurred when passing by value.


          > I tried the same program example with passing by value and it works perfectly fine.

          Which example are you referring to?

        • Bassam

          Passing classes by reference is good for performance. see <a href="https://">Passing arguments by reference</a>

      • Ace

        Alex I’m not getting where is Mr D passing the argument by value! Doesn’t the ‘&’ before the argument name cAccumulator in the function prototype

        indicate passing by reference?

  • Quang

    Hello Alex! I want to thank you for what you have done to the programming community! I have a little bit problem about the friend functions:
    - In 8.10 — Const class objects and member functions, you use functions like getDate, getMonth, getYear and i wonder whats the differences between those and friend function ( may be getSomething just for the return !? ) and what is the proper situation to use each of them?
    Thank you for reading this!! Keep up the great work

    • Alex

      Friend functions have direct access to the private data of a class. Non-friend functions have to use public accessor functions (like getMonth()).

      Friend functions are mostly useful for overloading operators, which we talk about in the next chapter. It’s generally good to keep your friend functions to a minimum and use accessors if you can.

  • anvekar

    Why is it necessary to use an argument in the function prototype inside the class?
    As it is just a prototype, only the argument type should be sufficient right?
    Example: friend void Reset( Accumulator& ); // prototype for the friend function Reset()

    • Alex

      In the above case, the argument is needed because function Reset() is not a member of class Accumulator.

      If Reset() were defined as a member of class Accumulator, then making it a friend would not be necessary, as it would already be able to access the private members of class Accumulator!

  • Enrique

    this website is a jewell for C++ programers. Thanks a lot !

  • Hi, this is an awesome website.
    I learn C++ here much faster than any other places.

    But I just got a little confuse here.
    The friend function, in my opinion, is something like a Getter or Setter.
    Is there any other usage which makes the friend function so important that it needs to be a feature of Cpp?
    Or, what’s the difference between a friend function and a ( normal function + Getter + Setter )

    Thanks 😀

    • Danny

      The getters and setters are usually member functions within a class. The setter initializes the data members, and getter can probably display the values set by the setter. For the friend functions, consider a case where you have all your data encapsulated within a class, but there is also a non-class function that needs to access the data in that class. (I used non-class function to clearly set the difference between friend functions and other normal functions)
      How would the non-class function access the data in the class? Making the non-class function a friend to the class by declaring its prototype in the class is the only. Otherwise,trying to access data would give you an error.
      I hope this helps.

  • Vaibhav

    Hi Alex,

    Just a question.
    Can a friend function be const or volatile.
    eg. friend void Reset(Accumulator &cAccumulator) const;
    friend volatile void Reset((Accumulator &cAccumulator);

  • samiullah

    Thank U so much Alex;

  • dinhpq

    Hi Alex,
    I have confused “A friend function may or may not be a member of another class” It mean member function Reset() of class Value may or may not be a friend class Accumulator, is that true? I have an example:

    The compiler error: undefined reference to `Value::Reset(Accumulator&)’
    Can you explain?

    • Alex

      I mean that a friend function may be either a normal function, or a member function of another class.

      In the above code, you’ve declared Reset() as a member of class Value, but you’ve defined Reset to not belong to a class. You will need to fix this, and then you will need to flip the order of the classes around, so class value is declared first (or put it in a header file).

  • Aki

    Normal friend functions can access private members of other classes.
    But if the friend function is a member function of another class then it cannot access the other class’s private members.

    friends.cpp: In member function ‘int B::boo(A&)’:
    friends.cpp:4:6: error: ‘int A::x’ is private
    friends.cpp:23:9: error: within this context

    • prakash

      // This works.


      class A; // forward declaration

      class B
      int y;
      int boo(A &a) ; // only declare. define later. as friendship has not came in to play yet.


      class A
      int x;
      friend int B::boo(A &a);
      x = 5;

      // now we define the function boo which belongs to class B only. just defined outside.
      // if using header files and implementation files separately, it makes crystal clear.

      int B::boo(A &a){
      y = a.x;
      return y;

      int main()
      using namespace std;
      A a;
      B b;
      cout << << endl;

      • prakash


        you can add more functions in class B, same as foo. i.e. declare first and define later.
        but keep friendship to foo.
        other functions will not have access to private x


  • lolo 33

    I’m so lucky to find this websit =)

    thnx so much Alex ,i have c++ exam now


  • asif

    can some one help me with this …..i tried compiling in Gnu G++ environment…and following are the errors…can someone tell me whats wrong with above code!!!111
    friend2.cpp:30: error: invalid use of incomplete type ‘struct two’
    friend2.cpp:5: error: forward declaration of ‘struct two’
    friend2.cpp: In member function ‘int two::accessboth(one)’:
    friend2.cpp:24: error: ‘int one::data1’ is private
    friend2.cpp:55: error: within this context

    • Alex

      Class one needs to see the full declaration of class two for a friend member function to work.

      You have a couple of options here:
      1) Use a friend class instead.
      2) Switch the order of the classes and define the functions outside of the classes (after the declarations).

  • Trevor

    Heya Alex, I really had better start by thanking you for this excellent site. Thanks.

    My question is: is it possible to make only one fuction in a Class A a friend of Class B without making the WHOLE of Class A a friend of Class B. I’ve constructed a crude example to show why I think it can’t be done, perhaps you can tell me if I’m doing something wrong:

    The code above works exactly as expected, but if I replace “friend class manipulate” with “friend int add(number &a,number &b)” or “friend int manipulate::add(number &a,number &b)”, I get compiler errors along the lines of “cannot access private member declared in class ‘number'”.



    • Alex

      Yes, it is possible, although with a little difficulty.

      I’ve updated the lesson with an example similar to this.

  • tyler

    hey Alex;

    great lessons, and thx for helping me back with the headers files.

    I would like to know how to make my program play music that i have on my computer, and dicplay pictures. when i saw ‘Object Oriented Programing’ thats what i though it was (useing picures in prgramsect…) gut i see that i was wrong. i would like to learn how to make those types of gams that you see on miniclip. ( i know i know, those games are made using flash, but i’m sure you can do simalar thins with C++, like they use C++ for games likie need for speed and the computer version of halo don’t they?)

  • Pathik

    Are all the codes you write now object-oriented programming?

  • why the errors this above code contain.plz explain .

  • K D Joshi

    Is it compulsory to declare a function(which is required to be a friend function) in that class itself?
    Suppose there is a class named FUN. It has some private and some public elements. Now I want a function called SOME to be a friend of FUN. So, is it MUST to declare SOME in private or public section of FUN? Or is it okey to declare and define it entirely outside the class with prefix friend.

  • jagadeesh

    c++ programm.
    member function of class can access private members,than we we need friend function,what is the use of this please iam in confusion

    • Making a function a friend of some class means that function has access to the classes private member variables (even though that function is not a member of the class). The Humidity/Weather example above shows an example of this: PrintWeather() is using the private members of Humidity and Weather (which it would normally not have access to, because they are private). However, it is allowed to do this because it has been made a friend.

  • sanjay

    hey its great to have a website like this
    i didn’t buy my cp book till my exams even then i stood 3rd in my class…


Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter