Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use 'friend' in C++?

People also ask

When should I use friend function?

They are used in situations where we want a certain class to have access to another class's private and protected members. Classes declared as friends to any another class will have all the member functions become friend functions to the friend class. Friend functions are used to work as a link between the classes.

What is the benefit of using friend function?

Advantages of Friend Function in C++ The friend function allows the programmer to generate more efficient codes. It allows the sharing of private class information by a non-member function. It accesses the non-public members of a class easily.

What is the use of friend concept?

A friend function can access the private and protected data of a class. We declare a friend function using the friend keyword inside the body of the class.

Why do we use friend class?

Use of Friend Class in C++Accessing private and protected members of other classes (as you would know by now) Declaring all the functions of a class as friend functions. Allowing to extend storage and access its part while maintaining encapsulation. Enabling classes to share private members' information.


Firstly (IMO) don't listen to people who say friend is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas.

There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions).

Onto the answer;

The friend specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name.

You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.

class Child
{
//Mother class members can access the private parts of class Child.
friend class Mother;

public:

  string name( void );

protected:

  void setName( string newName );
};

At work we use friends for testing code, extensively. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have separate test code that uses friends to inspect internal state and data for testing.

Suffice to say I wouldn't use the friend keyword as an essential component of your design.


The friend keyword has a number of good uses. Here are the two uses immediately visible to me:

Friend Definition

Friend definition allows to define a function in class-scope, but the function will not be defined as a member function, but as a free function of the enclosing namespace, and won't be visible normally except for argument dependent lookup. That makes it especially useful for operator overloading:

namespace utils {
    class f {
    private:
        typedef int int_type;
        int_type value;

    public:
        // let's assume it doesn't only need .value, but some
        // internal stuff.
        friend f operator+(f const& a, f const& b) {
            // name resolution finds names in class-scope. 
            // int_type is visible here.
            return f(a.value + b.value);
        }

        int getValue() const { return value; }
    };
}

int main() {
    utils::f a, b;
    std::cout << (a + b).getValue(); // valid
}

Private CRTP Base Class

Sometimes, you find the need that a policy needs access to the derived class:

// possible policy used for flexible-class.
template<typename Derived>
struct Policy {
    void doSomething() {
        // casting this to Derived* requires us to see that we are a 
        // base-class of Derived.
        some_type const& t = static_cast<Derived*>(this)->getSomething();
    }
};

// note, derived privately
template<template<typename> class SomePolicy>
struct FlexibleClass : private SomePolicy<FlexibleClass> {
    // we derive privately, so the base-class wouldn't notice that, 
    // (even though it's the base itself!), so we need a friend declaration
    // to make the base a friend of us.
    friend class SomePolicy<FlexibleClass>;

    void doStuff() {
         // calls doSomething of the policy
         this->doSomething();
    }

    // will return useful information
    some_type getSomething();
};

You will find a non-contrived example for that in this answer. Another code using that is in this answer. The CRTP base casts its this pointer, to be able to access data-fields of the derived class using data-member-pointers.


@roo: Encapsulation is not broken here because the class itself dictates who can access its private members. Encapsulation would only be broken if this could be caused from outside the class, e.g. if your operator << would proclaim “I'm a friend of class foo.”

friend replaces use of public, not use of private!

Actually, the C++ FAQ answers this already.


The canonical example is to overload operator<<. Another common use is to allow a helper or admin class access to your internals.

Here are a couple of guidelines I heard about C++ friends. The last one is particularly memorable.

  • Your friends are not your child's friends.
  • Your child's friends are not your friends.
  • Only friends can touch your private parts.

edit: Reading the faq a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes, however I am not sure how this doesn't break encapsulation

How would it break encapsulation?

You break encapsulation when you allow unrestricted access to a data member. Consider the following classes:

class c1 {
public:
  int x;
};

class c2 {
public:
  int foo();
private:
  int x;
};

class c3 {
  friend int foo();
private:
  int x;
};

c1 is obviously not encapsulated. Anyone can read and modify x in it. We have no way to enforce any kind of access control.

c2 is obviously encapsulated. There is no public access to x. All you can do is call the foo function, which performs some meaningful operation on the class.

c3? Is that less encapsulated? Does it allow unrestricted access to x? Does it allow unknown functions access?

No. It allows precisely one function to access the private members of the class. Just like c2 did. And just like c2, the one function which has access is not "some random, unknown function", but "the function listed in the class definition". Just like c2, we can see, just by looking at the class definitions, a complete list of who has access.

So how exactly is this less encapsulated? The same amount of code has access to the private members of the class. And everyone who has access is listed in the class definition.

friend does not break encapsulation. It makes some Java people programmers feel uncomfortable, because when they say "OOP", they actually mean "Java". When they say "Encapsulation", they don't mean "private members must be protected from arbitrary accesses", but "a Java class where the only functions able to access private members, are class members", even though this is complete nonsense for several reasons.

First, as already shown, it is too restricting. There's no reason why friend methods shouldn't be allowed to do the same.

Second, it is not restrictive enough. Consider a fourth class:

class c4 {
public:
  int getx();
  void setx(int x);
private:
  int x;
};

This, according to aforesaid Java mentality, is perfectly encapsulated. And yet, it allows absolutely anyone to read and modify x. How does that even make sense? (hint: It doesn't)

Bottom line: Encapsulation is about being able to control which functions can access private members. It is not about precisely where the definitions of these functions are located.


Another common version of Andrew's example, the dreaded code-couplet

parent.addChild(child);
child.setParent(parent);

Instead of worrying if both lines are always done together and in consistent order you could make the methods private and have a friend function to enforce consistency:

class Parent;

class Object {
private:
    void setParent(Parent&);

    friend void addChild(Parent& parent, Object& child);
};

class Parent : public Object {
private:
     void addChild(Object& child);

     friend void addChild(Parent& parent, Object& child);
};

void addChild(Parent& parent, Object& child) {
    if( &parent == &child ){ 
        wetPants(); 
    }
    parent.addChild(child);
    child.setParent(parent);
}

In other words you can keep the public interfaces smaller and enforce invariants that cut across classes and objects in friend functions.