Search

Language Selector

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 declaration for the class of the friend member function (not just a forward declaration). Since class Storage hasn’t seen the full declaration for class Display yet, the compiler will error at the point where we try to make the member function a friend.

To resolve this, we can switch the order of class Display and class Storage. We will also need to move the definition of Display::displayItem() out of the Display class declaration, because it needs to have seen the definition of class Storage first.

Now, this will compile, and Display::displayItem is a friend of class Storage.

However, a better solution would have been to put each class declaration in a separate header file, with the function bodies in corresponding .cpp files. That way, all of the class declarations would have been visible immediately, and no rearranging of classes or functions would have been necessary.

Summary

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 as forward declaration that the class exists. However, making a specific member function a friend requires the full declaration 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 Vector3d a friend class of Point3d, 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

8.14 -- Anonymous variables and objects
Index
8.12 -- Static member functions

51 comments to 8.13 — Friend functions and classes

  • 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…


    sanjay

  • 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.

  • 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.

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

  • Pathik

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

  • 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?)

  • 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'”.

    Cheers,

    Trevor

    • Alex

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

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

  • 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).

  • lolo 33

    I’m so lucky to find this websit =)

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

    bye

  • 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.

      #include
      #include

      class A; // forward declaration

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

      };

      class A
      {
      int x;
      public:
      friend int B::boo(A &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 << b.boo(a) << endl;
      }

      • prakash

        Aki,

        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

        -prakash

  • 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).

  • samiullah

    Thank U so much Alex;

  • 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);

  • 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 😀
    Ma

    • 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.

  • Enrique

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

  • 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!

  • 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.

  • 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.

          True.

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

          Which example are you referring to?

  • 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’
    and
    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:

  • 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?

  • Lokesh

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

  • Lokesh

    In first code example in this lesson,

    should be

  • Lokesh

    Quiz 1a. solution - line 20

    should be

Leave a Comment

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

  

  

  

3 × three =