Search

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 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! 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 or may not be a member 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_nValue 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.

While this example is pretty contrived, here’s another example that’s a lot closer to something you’ll see again in the near future, when we talk about operator overloading:

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.

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. Here’s a simple program that shows the above classes in use:

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.

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

55 comments to 8.13 — Friend functions and classes

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

    #include 
    using namespace std;
    
    class Accumulator
    {
    private:
        int m_nValue;
    public:
        Accumulator() { m_nValue = 0; }
        void Add(int nValue) { m_nValue += nValue; } 
        friend void Reset(Accumulator &cAccumulator);
    };
     
    class Value
    {
    private:
        int m_nValue;
    public:
        Value(int nValue) { m_nValue = nValue; }
        void Reset(Accumulator &cAccumulator);
    };
    void Reset(Accumulator &cAccumulator)
    {
        cout << "Reset Accumulator" <<endl;
        cAccumulator.m_nValue = 0;
    } 
    int main()
    {
    	Accumulator cAccumulator;
    	Value cValue(10);
    	cValue.Reset(cAccumulator);
       return 0;
    }
    

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

  • nadia.16

    come posso risolvere qlkn mi dà una mano?

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">