By roo

2008-08-20 05:29:32 8 Comments

I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

What is a good example of using friend?

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. When can these exceptions stay within the strictness that is OOP?


@lixunhuan 2017-08-18 03:27:19

As the reference for friend declaration says:

The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears.

So just as a reminder, there are technical errors in some of the answers which say that friend can only visit protected members.

@Francis Cugler 2017-02-12 11:36:28

This may not be an actual use case situation but may help to illustrate the use of friend between classes.

The ClubHouse

class ClubHouse {
    friend class VIPMember; // VIP Members Have Full Access To Class
    unsigned nonMembers_;
    unsigned paidMembers_;
    unsigned vipMembers;

    std::vector<Member> members_;
    ClubHouse() : nonMembers_(0), paidMembers_(0), vipMembers(0) {}

    addMember( const Member& member ) { // ...code }   
    void updateMembership( unsigned memberID, Member::MembershipType type ) { // ...code }
    Amenity getAmenity( unsigned memberID ) { // ...code }

    void joinVIPEvent( unsigned memberID ) { // ...code }

}; // ClubHouse

The Members Class's

class Member {
    enum MemberShipType {
        NON_MEMBER_PAID_EVENT,   // Single Event Paid (At Door)
        PAID_MEMBERSHIP,         // Monthly - Yearly Subscription
        VIP_MEMBERSHIP,          // Highest Possible Membership
    }; // MemberShipType

    MemberShipType type_;
    unsigned id_;
    Amenity amenity_;
    Member( unsigned id, MemberShipType type ) : id_(id), type_(type) {}
    virtual ~Member(){}
    unsigned getId() const { return id_; }
    MemberShipType getType() const { return type_; }
    virtual void getAmenityFromClubHouse() = 0       

class NonMember : public Member {
   explicit NonMember( unsigned id ) : Member( id, MemberShipType::NON_MEMBER_PAID_EVENT ) {}   

   void getAmenityFromClubHouse() override {
       Amenity = ClubHouse::getAmenity( this->id_ );

class PaidMember : public Member {
    explicit PaidMember( unsigned id ) : Member( id, MemberShipType::PAID_MEMBERSHIP ) {}

    void getAmenityFromClubHouse() override {
       Amenity = ClubHouse::getAmenity( this->id_ );

class VIPMember : public Member {
    friend class ClubHouse;
    explicit VIPMember( unsigned id ) : Member( id, MemberShipType::VIP_MEMBERSHIP ) {}

    void getAmenityFromClubHouse() override {
       Amenity = ClubHouse::getAmenity( this->id_ );

    void attendVIPEvent() {
        ClubHouse::joinVIPEvent( this->id );


class Amenity{};

If you look at the relationship of these classes here; the ClubHouse holds a variety of different types of memberships and membership access. The Members are all derived from a super or base class since they all share an ID and an enumerated type that are common and outside classes can access their IDs and Types through access functions that are found in the base class.

However through this kind of hierarchy of the Members and its Derived classes and their relationship with the ClubHouse class the only one of the derived class's that has "special privileges" is the VIPMember class. The base class and the other 2 derived classes can not access the ClubHouse's joinVIPEvent() method, yet the VIP Member class has that privilege as if it has complete access to that event.

So with the VIPMember and the ClubHouse it is a two way street of access where the other Member Classes are limited.

@Daemin 2008-08-30 09:59:53

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.

@Jon Cage 2011-11-03 16:51:13

That's exactly what I use it for. That or just set the member variables to protected. It's just a shame it doesn't work for C++/CLI :-(

@Graeme 2012-09-06 22:04:28

Personally I would discourage this. Typically you are testing an interface, i.e. does a set of inputs give the expected set of output(s). Why do you need to inspect internal data?

@Ben Voigt 2013-04-29 00:30:46

@Graeme: Because a good test plan includes both white box and black box testing.

@Alexis Leclerc 2015-10-09 21:46:31

I tend to agree with @Graeme, as explained perfectly in this answer.

@Francis Cugler 2017-02-12 10:46:29

@Graeme it may not be internal data directly. I may be a method that performs a specific operation or task on that data where that method is private to the class and shouldn't be publicly accessible while some other object may have need to feed or seed that class's protected method with its own data.

@Brian Howell 2017-08-10 15:53:10

I've often used traces (basically printf) for this kind of testing

@GamefanA 2018-05-09 00:09:30

And that's why nobody want's to be friends with programmers.

@Andrew Grant 2008-08-20 05:48:22

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;


  string name( void );


  void setName( string newName );

@André Caron 2010-10-21 18:28:44

As an extra note, the C++ FAQ mentions that friend enhances encapsulation. friend grants selective access to members, just like protected does. Any fine-grained control is better than granting public access. Other languages define selective access mechanisms too, consider C#'s internal. Most negative criticism around the use of friend is related to tighter coupling, which is generally seen as a bad thing. However, in some cases, tighter coupling is precisely what you want and friend gives you that power.

@OmarOthman 2011-11-22 07:47:17

Could you please say more about (cpp-level concrete classes) and (masked typedefs), Andrew?

@bames53 2012-12-28 23:56:44

This answer seems to be more focused on explaining what friend is rather than providing a motivating example. The Window/WindowManager example is better than the example shown, but too vague. This answer also does not address the encapsulation portion of the question.

@Peng Zhang 2014-05-03 21:08:08

For the Window/WindowManger exmaple, why not we have pointers of Window as attributes in the WindowManager? I think this is better than declaring WindowManager as a "friend" to Window.

@weberc2 2014-06-17 18:48:01

So effectively 'friend' exists because C++ has no notion of a package in which all members may share implementation details? I would be really interested in a real-world example.

@OMGtechy 2014-07-31 06:50:40

@weberc2 I currently use friend so that my MessageBus can access private members of MessageHandler without exposing them to everything else.

@weberc2 2014-07-31 15:03:09

@OMGtechy You wouldn't have to do that if C++ had a notion of packages, so it's consistent with my previous statement. Here's an example in Go that uses packages instead of friends to access private members:

@Jo So 2014-08-29 13:50:12

I think the Mother / Child example is unfortunate. These names are suitable for instances, but not for classes. (The problem shows if we have 2 mothers, and each has their own child).

@TalL 2015-01-08 10:00:00

For me, friend functions are closely tied to implementing comparison methods between objects that needs access to private members in order to do their jobs. Friend classes are a little rare (where I come from), but a good use I found for it is having a broadcast manager that everyone can listen to, but only a select few can add a message to broadcast. The one with the privilege to broadcast are friend classes.

@iheanyi 2015-03-09 15:35:59

@weberc2 you wouldn't have to do that if Go had friends instead of packages.

@weberc2 2015-03-09 15:48:03

@iheanyi There are a lot of best practices I wouldn't have to follow if Go encouraged worse practices, but I'm not really sure how that relates to the subject at hand...

@iheanyi 2015-03-10 14:23:53

@weberc I don't know what "bad practice" C++ encourages, in general, or specifically in the context of friendship. Saying "well in Go, one would just use x instead of y from C++" is meaningless - especially given that x and y are mutually exclusive features of the two languages.

@weberc2 2015-03-10 14:32:59

@iheanyi Friendship encourages violations of encapsulation. Instead of injecting dependencies, I often see developers new() up their class's collaborators within the class and then expose them to tests via friendship (instead of dependency injection, for example). This leads to conflating responsibilities within the same class (object graph construction/destruction + whatever the class's actual responsibility is). A couple of people even answered this question with similar suggestions below:

@iheanyi 2015-03-10 15:09:30

@weberc By that logic, global variables also encourage violations of encapsulation. I suppose Go doesn't have those either? That programmers can misuse something doesn't mean the language encourages it. As far as I can tell, the language intends friendship to enhance encapsulation. I use friendship to limit external access to data or methods of a class. The only person encouraging violations of encapsulation when they use friendship is the programmer who misused it in the first place.

@weberc2 2015-03-10 15:14:05

@iheanyi No, you reasoned incorrectly--I never said that Go doesn't support any bad practices, I just said there were a lot of bad practices that Go discourages. Similarly, I wasn't arguing that friendship can't be used appropriately--my argument was that it's very easy to abuse (more so than many other abusable features), as evidenced by many of the answers in this thread.

@iheanyi 2015-03-10 16:22:27

@weberc I just read through most of all the other answers and while there are only a few that are comprehensive, most of them do give correct, limited ways, to properly use friendship in C++. I don't see how it's easier to abuse than many other things in the language. Plenty of people think they how how to declare variables and arrays, deference pointers, or handle memory and fail at this all the time. At best, one can say "C++ makes it easy to shoot yourself in the foot". But regardless of how easy it is, it doesn't mean you're encouraged to do it.

@weberc2 2015-03-10 16:41:14

@iheanyi I just read through the list myself. Most of the "reasons to use friend" pertain to unit testing, singletons, and generally "convenience encapsulation violations" (which hardly seems better than making all of your internals public)--these things are all considered bad practice in the broader OOP community. There are also a few correct answers, most notably "use friend when it improves encapuslation" and this answer that we're commenting on. For posterity's sake, a few questions were not actually answers but arguments about semantics.

@weberc2 2015-03-10 16:43:27

@iheanyi There were a few answers that might be correct, like the template answer and limiting inheritance--I don't know about the former and the latter sounds like a hack (and I don't know why an object would want to limit its inheritance--that sounds like an object-graph detail to me).

@Francis Cugler 2017-02-12 10:44:01

It's always good to have friends; without them you would be alone in the world! We are in this together, however some things are meant to be left as private (our privacy) while other things we share amongst friends.

@peterdcasey 2016-04-07 20:01:40

Probably I missed something from the answers above but another important concept in encapsulation is hiding of implementation. Reducing access to private data members (the implementation details of a class) allows much easier modification of the code later. If a friend directly accesses the private data, any changes to the implementation data fields (private data), break the code accessing that data. Using access methods mostly eliminates this. Fairly important I would think.

@Shiv 2016-03-25 17:53:35

In C++ "friend" keyword is useful in Operator overloading and Making Bridge.

1.) Friend keyword in operator overloading :
Example for operator overloading is: Let say we have a class "Point" that has two float variable
"x"(for x-coordinate) and "y"(for y-coordinate). Now we have to overload "<<"(extraction operator) such that if we call "cout << pointobj" then it will print x and y coordinate (where pointobj is an object of class Point). To do this we have two option:

   1.Overload "operator <<()" function in "ostream" class.
   2.Overload "operator<<()" function in "Point" class.
Now First option is not good because if we need to overload again this operator for some different class then we have to again make change in "ostream" class.
That's why second is best option. Now compiler can call "operator <<()" function:

   1.Using ostream object cout.As: cout.operator<<(Pointobj) (form ostream class).
2.Call without an object.As: operator<<(cout, Pointobj) (from Point class).

Beacause we have implemented overloading in Point class. So to call this function without an object we have to add"friend" keyword because we can call a friend function without an object. Now function declaration will be As:
"friend ostream &operator<<(ostream &cout, Point &pointobj);"

2.) Friend keyword in making bridge :
Suppose we have to make a function in which we have to access private member of two or more classes ( generally termed as "bridge" ) . How to do this:
To access private member of a class it should be member of that class. Now to access private member of other class every class should declare that function as a friend function. For example : Suppose there are two class A and B. A function "funcBridge()" want to access private member of both classes. Then both class should declare "funcBridge()" as:
friend return_type funcBridge(A &a_obj, B & b_obj);

I think this would help to understand friend keyword.

@rptony 2008-08-25 12:11:39

Friend comes handy when you are building a container and you want to implement an iterator for that class.

@Konrad Rudolph 2008-08-20 07:16:26

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

@Waleed Eissa 2009-05-10 05:56:52

"friend replaces use of public, not use of private!", I second that

@Konrad Rudolph 2009-12-27 21:28:18

@Assaf: yes, but the FQA is, for the most part a, a lot of incoherent angry gibberish without any real value. The part on friend is no exception. The only real observation here is that C++ ensures encapsulation at compile-time only. And you don’t need any more words to say it. The rest is bollocks. So, in summary: this section of the FQA is not worth mentioning.

@rama-jka toti 2010-01-15 07:19:23

Most of that FQA is utter blx :)

@André Caron 2010-10-21 18:32:36

@Konrad: "The only real observation here is that C++ ensures encapsulation at compile-time only." Do any languages ensure this at runtime? As far as I know, returning references to private members (and functions, for languages who allow pointers to functions or functions as first class objects) is allowed in C#, Java, Python and many others.

@Konrad Rudolph 2010-10-21 21:01:56

@André: the JVM and the CLR actually can ensure this as far as I know. I don’t know if it’s always done but you can allegedly protect packages/assemblies against such intrusion (never done this myself though).

@André Caron 2010-10-21 21:24:47

@Konrad: technically, any VM-type environment with access to the call stack can validate this fairly easily, but I think it would break a lot of existing code. For instance, I regularly declare observer callbacks as private in C# so that I can control where they are registered. I mean, if your object returns a reference to data members or member functions, it is at its own risk. I don't see any advantage in such limitations, only loss of the power to grant fine-grained selective access.

@Konrad Rudolph 2010-10-21 21:29:20

@André: a privately declared delegate doesn’t break encapsulation in the slightest. It would still work just fine with an access-controlling runtime because it’s well-defined within the type system. What would be forbidden (and checked for) would be tries to subvert the type system, using either reflection or C#’s unsafe feature. – Just to make this clear, I’m operating on hearsay, I’ve never actually tried to use these security features. But if they weren’t in place, then a lot of .NET’s security policy framework wouldn’t make any sense.

@André Caron 2010-10-21 21:40:33

@Konrad: if, by using the unsafe blocks, you mean the equivalent of casting to unsigned char * and using the member offset to access private members anyways, then I agree with you that C++ doesn't check for this at runtime. In .NET's case, I don't think any specific check to enforce encapsulation needs to be done because you won't be able to case any "pointer+offset" to an object reference anyways.

@curiousguy 2011-12-23 07:05:32

@AndréCaron "Do any languages ensure this at runtime?" Any language with strong reflective capabilities, and the aim of being "type safe", should better check encapsulation at runtime!

@Nawaz 2012-02-27 05:55:09

+1 for ". 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.”". Nice one!

@VladimirS 2015-02-19 19:34:00

I found handy place to use friend access: Unittest of private functions.

@Zheng Qu 2016-07-15 10:03:05

But can a public function also be used for that? What is the advantage of using friend access?

@VladimirS 2016-07-15 17:12:41

@Maverobot Could you elaborate on your question?

@kiriloff 2014-02-06 09:50:38

You may use friendship when different classes (not inheriting one from the other) are using private or protected members of the other class.

Typical use cases of friend functions are operations that are conducted between two different classes accessing private or protected members of both.

from .

You can see this example where non-member method accesses the private members of a class. This method has to be declared in this very class as a friend of the class.

// friend functions
#include <iostream>
using namespace std;

class Rectangle {
    int width, height;
    Rectangle() {}
    Rectangle (int x, int y) : width(x), height(y) {}
    int area() {return width * height;}
    friend Rectangle duplicate (const Rectangle&);

Rectangle duplicate (const Rectangle& param)
  Rectangle res;
  res.width = param.width*2;
  res.height = param.height*2;
  return res;

int main () {
  Rectangle foo;
  Rectangle bar (2,3);
  foo = duplicate (bar);
  cout << foo.area() << '\n';
  return 0;

@Ephemera 2012-12-29 02:55:28

You have to be very careful about when/where you use the friend keyword, and, like you, I have used it very rarely. Below are some notes on using friend and the alternatives.

Let's say you want to compare two objects to see if they're equal. You could either:

  • Use accessor methods to do the comparison (check every ivar and determine equality).
  • Or, you could access all the members directly by making them public.

The problem with the first option, is that that could be a LOT of accessors, which is (slightly) slower than direct variable access, harder to read, and cumbersome. The problem with the second approach is that you completely break encapsulation.

What would be nice, is if we could define an external function which could still get access to the private members of a class. We can do this with the friend keyword:

class Beer {
    friend bool equal(Beer a, Beer b);
    // ...

The method equal(Beer, Beer) now has direct access to a and b's private members (which may be char *brand, float percentAlcohol, etc. This is a rather contrived example, you would sooner apply friend to an overloaded == operator, but we'll get to that.

A few things to note:

  • A friend is NOT a member function of the class
  • It is an ordinary function with special access to the private members of the class
  • Don't replace all accessors and mutators with friends (you may as well make everything public!)
  • Friendship isn't reciprocal
  • Friendship isn't transitive
  • Friendship isn't inherited
  • Or, as the C++ FAQ explains: "Just because I grant you friendship access to me doesn't automatically grant your kids access to me, doesn't automatically grant your friends access to me, and doesn't automatically grant me access to you."

I only really use friends when it's much harder to do it the other way. As another example, many vector maths functions are often created as friends due to the interoperability of Mat2x2, Mat3x3, Mat4x4, Vec2, Vec3, Vec4, etc. And it's just so much easier to be friends, rather than have to use accessors everywhere. As pointed out, friend is often useful when applied to the << (really handy for debugging), >> and maybe the == operator, but can also be used for something like this:

class Birds {
    friend Birds operator +(Birds, Birds);
    int numberInFlock;

Birds operator +(Birds b1, Birds b2) {
    Birds temp;
    temp.numberInFlock = b1.numberInFlock + b2.numberInFlock;
    return temp;

As I say, I don't use friend very often at all, but every now and then it's just what you need. Hope this helps!

@Lubo Antonov 2012-03-28 14:08:56

Friend functions and classes provide direct access to private and protected members of class to avoid breaking encapsulation in the general case. Most usage is with ostream: we would like to be able to type:

Point p;
cout << p;

However, this may require access to the private data of Point, so we define the overloaded operator

friend ostream& operator<<(ostream& output, const Point& p);

There are obvious encapsulation implications, however. First, now the friend class or function has full access to ALL members of the class, even ones that do not pertain to its needs. Second, the implementations of the class and the friend are now enmeshed to the point where an internal change in the class can break the friend.

If you view the friend as an extension of the class, then this is not an issue, logically speaking. But, in that case, why was it necessary to spearate out the friend in the first place.

To achieve the same thing that 'friends' purport to achieve, but without breaking encapsulation, one can do this:

class A
    void need_your_data(B & myBuddy)
    string name_;

class B
    void print_buddy_name(A & myBuddy)
    void take_this_name(const string & name)
        cout << name;

Encapsulation is not broken, class B has no access to the internal implementation in A, yet the result is the same as if we had declared B a friend of A. The compiler will optimize away the function calls, so this will result in the same instructions as direct access.

I think using 'friend' is simply a shortcut with arguable benefit, but definite cost.

@popopome 2008-08-20 08:32:26

To do TDD many times I've used 'friend' keyword in C++.

Can a friend know everything about me?

Updated: I found this valuable answer about "friend" keyword from Bjarne Stroustrup site.

"Friend" is an explicit mechanism for granting access, just like membership.

@garzanti 2010-02-11 14:42:53

The creator of C++ says that isn't broking any encapsulation principle, and I will quote him:

Does "friend" violate encapsulation? No. It does not. "Friend" is an explicit mechanism for granting access, just like membership. You cannot (in a standard conforming program) grant yourself access to a class without modifying its source.

Is more than clear...

@Nawaz 2012-02-27 06:09:29

@curiousguy: Even in case of templates, it is true.

@curiousguy 2012-03-05 02:18:02

@Nawaz Template friendship may be granted, but anyone can make a new partial or explicit specialization without modifying the friendship granting class. But be careful with ODR violations when you do that. And do not do that anyway.

@Gian Paolo Ghilardi 2009-09-07 09:38:07

Another use: friend (+ virtual inheritance) can be used to avoid deriving from a class (aka: "make a class underivable") => 1, 2

From 2:

 class Fred;

 class FredBase {
   friend class Fred;
   FredBase() { }

 class Fred : private virtual FredBase {

@jalf 2009-09-07 09:24:47

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 {
  int x;

class c2 {
  int foo();
  int x;

class c3 {
  friend int foo();
  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 {
  int getx();
  void setx(int x);
  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.

@larsmoa 2009-09-07 09:03:21

I'm only using the friend-keyword to unittest protected functions. Some will say that you shouldn't test protected functionality. I, however, find this very useful tool when adding new functionality.

However, I don't use the keyword in directly in the class declarations, instead I use a nifty template-hack to achive this:

template<typename T>
class FriendIdentity {
  typedef T me;

 * A class to get access to protected stuff in unittests. Don't use
 * directly, use friendMe() instead.
template<class ToFriend, typename ParentClass>
class Friender: public ParentClass
  Friender() {}
  virtual ~Friender() {}
// MSVC != GCC
#ifdef _MSC_VER
  friend ToFriend;
  friend class FriendIdentity<ToFriend>::me;

 * Gives access to protected variables/functions in unittests.
 * Usage: <code>friendMe(this, someprotectedobject).someProtectedMethod();</code>
template<typename Tester, typename ParentClass>
Friender<Tester, ParentClass> & 
friendMe(Tester * me, ParentClass & instance)
    return (Friender<Tester, ParentClass> &)(instance);

This enables me to do the following:

friendMe(this, someClassInstance).someProtectedFunction();

Works on GCC and MSVC atleast.

@Gorpik 2009-01-16 08:33:42

The short answer would be: use friend when it actually improves encapsulation. Improving readability and usability (operators << and >> are the canonical example) is also a good reason.

As for examples of improving encapsulation, classes specifically designed to work with the internals of other classes (test classes come to mind) are good candidates.

@curiousguy 2011-12-23 06:57:27

"operators << and >> are the canonical example" No. Rather canonical counter examples.

@Gorpik 2012-01-02 09:21:11

@curiousguy: operators << and >> are usually friends, instead of members, because making them members would make them awkward to use. Of course, I am talking about the case when those operators need to access private data; otherwise, friendship is useless.

@curiousguy 2012-02-18 04:49:45

"because making them members would make them awkward to use." Obviously, making operator<< and operator>> members of the value class instead of non-members, or members of i|ostream, wouldn't provide the desired syntax, and I am not suggesting it. "I am talking about the case when those operators need to access private data" I don't quite see why the input/output operators would need to access private members.

@Johannes Schaub - litb 2008-12-13 15:49:08

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 {
        typedef int int_type;
        int_type value;

        // 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

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

@bennedich 2012-10-22 14:30:59

Hi, I get a syntax error (in xcode 4) when I try out your CRTP. Xcode believes I'm trying to inherit a class template. The error occurs at P<C> in template<template<typename> class P> class C : P<C> {}; stating "Use of class template C requires template arguments". Have you hade the same problems or perhaps know a solution?

@Yakk - Adam Nevraumont 2012-12-29 17:44:54

@bennedich at first glance, that looks like the kind of error you'd get with insufficient C++ feature support. Which is pretty common among compilers. The use of FlexibleClass within FlexibleClass should implicitly refers to its own type.

@Ben Voigt 2013-04-29 00:33:31

@bennedich: The rules for use of a class template's name from within the class body changed with C++11. Try enabling C++11 mode in your compiler.

@Damian 2016-03-29 07:06:04

In Visual Studio 2015 add this public: f() {}; f(int_type t) : value(t) {}; To prevent this compiler error: error C2440: '<function-style-cast>': cannot convert from 'utils::f::int_type' to 'utils::f' note: No constructor could take the source type, or constructor overload resolution was ambiguous

@shash 2008-12-12 12:10:05

Friends are also useful for callbacks. You could implement callbacks as static methods

class MyFoo
    static void callback(void * data, void * clientData);
    void localCallback();

where callback calls localCallback internally, and the clientData has your instance in it. In my opinion,


class MyFoo
    friend void callback(void * data, void * callData);
    void localCallback();

What this allows is for the friend to be a defined purely in the cpp as a c-style function, and not clutter up the class.

Similarly, a pattern I've seen very often is to put all the really private members of a class into another class, which is declared in the header, defined in the cpp, and friended. This allows the coder to hide a lot of the complexity and internal working of the class from the user of the header.

In the header:

class MyFooPrivate;
class MyFoo
    friend class MyFooPrivate;
    // Public stuff
    MyFooPrivate _private;
    // Other private members as needed

In the cpp,

class MyFooPrivate
   MyFoo *owner;
   // Your complexity here

    this->_private->owner = this;

It becomes easier to hide things that the downstream needn't see this way.

@JBRWilkinson 2009-09-07 10:02:15

Wouldn't interfaces be a cleaner way to achieve this? What's to stop someone looking up MyFooPrivate.h?

@shash 2009-09-16 07:12:54

Well, if you're using private and public to keep secrets, you're going to be defeated easily. By "hiding", I mean, the user of MyFoo doesn't really need to see the private members. Besides this, it's useful to maintain ABI compatibility. If you make _private a pointer, the private implementation can change as much as you want, without touching the public interface, thereby keeping ABI compatibility.

@weberc2 2015-03-10 16:52:39

You're referring to the PIMPL idiom; the purpose for which isn't additional encapsulation like you seem to be saying, but to move the implementation details out of the header so changing an implementation detail doesn't force a recompilation of client code. Further, there's no need to use friend to implement this idiom.

@shash 2015-03-11 06:05:24

Well, yes. Its main purpose is to move implementation details. The friend there is useful to handle private members inside the public class from the private or the other way around.

@maccullt 2008-09-10 02:52:54

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


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 {
    void setParent(Parent&);

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

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

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

void addChild(Parent& parent, Object& child) {
    if( &parent == &child ){ 

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

@Nawaz 2012-02-27 06:01:50

Why would anyone need a friend for that? Why not let addChild member function also set the parent?

@Ylisar 2014-02-26 15:23:43

A better example would be making setParent a friend, as you don't want to allow clients to change the parent since you'll be managing it in the addChild/removeChild category of functions.

@Ray 2008-09-04 23:43:46

We had an interesting issue come up at a company I previously worked at where we used friend to decent affect. I worked in our framework department we created a basic engine level system over our custom OS. Internally we had a class structure:

        /    \
 TwoPlayer  SinglePlayer

All of these classes were part of the framework and maintained by our team. The games produced by the company were built on top of this framework deriving from one of Games children. The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes. The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship.

Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had.

@Tanton 2008-08-21 13:03:12

With regards to operator<< and operator>> there is no good reason to make these operators friends. It is true that they should not be member functions, but they don't need to be friends, either.

The best thing to do is create public print(ostream&) and read(istream&) functions. Then, write the operator<< and operator>> in terms of those functions. This gives the added benefit of allowing you to make those functions virtual, which provides virtual serialization.

@curiousguy 2011-12-23 06:59:59

"With regards to operator<< and operator>> there is no good reason to make these operators friends." Absolutely correct. "This gives the added benefit of allowing you to make those functions virtual," If the class in question is intended for derivation, yes. Otherwise, why bother?

@curiousguy 2011-12-23 07:00:49

I really don't get why this answer was downvoted twice - and without even an explanation! That's rude.

@paulm 2015-04-21 14:28:24

virtual would add a perf hit which could be quite large in serialization

@Matt Dillard 2008-08-20 13:40:41

One specific instance where I use friend is when creating Singleton classes. The friend keyword lets me create an accessor function, which is more concise than always having a "GetInstance()" method on the class.

// Header file
class MySingleton
    // Private c-tor for Singleton pattern
    MySingleton() {}

    friend MySingleton& GetMySingleton();

// Accessor function - less verbose than having a "GetInstance()"
//   static function on the class
MySingleton& GetMySingleton();

// Implementation file
MySingleton& GetMySingleton()
    static MySingleton theInstance;
    return theInstance;

@Gorpik 2009-01-16 08:25:06

This may be a matter of taste, but I don't think saving a few keystrokes justifies the use of friend here. GetMySingleton() should be a static method of the class.

@JBRWilkinson 2009-09-07 09:59:51

The private c-tor would disallow a non-friend function to instantiate the MySingleton, so the friend keyword is needed here.

@curiousguy 2011-12-23 07:02:23

@Gorpik "This may be a matter of taste, but I don't think saving a few keystrokes justifies the use of friend here." It does. Anyway, friend does not need a particular "justification", when adding a member function doesn't.

@weberc2 2015-03-10 16:56:44

Singletons are considered a bad practice anyway (Google "singleton harmful" and you'll get lots of results like this. I don't think using a feature to implement an antipattern can be considered a good use of that feature.

@roo 2008-08-20 09:19:44

To do TDD many times I've used 'friend' keyword in C++.
Can a friend know everything about me?

No, its only a one way friendship :`(

@Mark Cidade 2008-08-20 07:46:14

You could adhere to the strictest and purest OOP principles and ensure that no data members for any class even have accessors so that all objects must be the only ones that can know about their data with the only way to act on them is through indirect messages, i.e., methods.

But even C# has an internal visibility keyword and Java has its default package level accessibility for some things. C++ comes actually closer to the OOP ideal by minimizinbg the compromise of visibility into a class by specifying exactly which other class and only other classes could see into it.

I don't really use C++ but if C# had friends I would that instead of the assembly-global internal modifier, which I actually use a lot. It doesn't really break incapsulation, because the unit of deployment in .NET is an assembly.

But then there's the InternalsVisibleToAttribute(otherAssembly) which acts like a cross-assembly friend mechanism. Microsoft uses this for visual designer assemblies.

@Mark Harrison 2008-08-20 07:05:04

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.

@curiousguy 2011-12-23 07:06:06

"The canonical example is to overload operator<<." The canonical of not using friend I guess.

@csmba 2008-08-20 06:10:58

You control the access rights for members and functions using Private/Protected/Public right? so assuming the idea of each and every one of those 3 levels is clear, then it should be clear that we are missing something...

The declaration of a member/function as protected for example is pretty generic. You are saying that this function is out of reach for everyone (except for an inherited child of course). But what about exceptions? every security system lets you have some type of 'white list" right?

So friend lets you have the flexibility of having rock solid object isolation, but allows for a "loophole" to be created for things that you feel are justified.

I guess people say it is not needed because there is always a design that will do without it. I think it is similar to the discussion of global variables: You should never use them, There is always a way to do without them... but in reality, you see cases where that ends up being the (almost) most elegant way... I think this is the same case with friends.

It doesn't really do any good, other than let you access a member variable without using a setting function

well that is not exactly the way to look at it. The idea is to control WHO can access what, having or not a setting function has little to do with it.

@jalf 2009-09-07 09:26:30

How is friend a loophole? It lets the methods listed in the class access its private members. It still doesn't let arbitrary code access them. As such it is no different from a public member function.

@Ogre Psalm33 2010-10-20 13:46:31

friend is as close as you can get to C#/Java package-level access in C++. @jalf - what about friend classes (such as a factory class)?

@jalf 2010-10-20 22:55:13

@Ogre: What about them? You're still specifically giving that class and no one else access to the class' internals. You're not just leaving the gate open for arbitrary unknown code to screw with your class.

@fulmicoton 2008-08-20 05:51:21

The tree example is a pretty good example : Having an object implemented in a few different class without having an inheritance relationship.

Maybe you could also need it to have a constructor protected and force people to use your "friend" factory.

... Ok, Well frankly you can live without it.

@Ryan Fox 2008-08-20 05:33:58

When implementing tree algorithms for class, the framework code the prof gave us had the tree class as a friend of the node class.

It doesn't really do any good, other than let you access a member variable without using a setting function.

Related Questions

Sponsored Content

19 Answered Questions

[SOLVED] How can I profile C++ code running on Linux?

  • 2008-12-17 20:29:24
  • Gabriel Isenberg
  • 522994 View
  • 1815 Score
  • 19 Answer
  • Tags:   c++ linux profiling

13 Answered Questions

[SOLVED] What is a smart pointer and when should I use one?

39 Answered Questions

22 Answered Questions

[SOLVED] What is the "-->" operator in C++?

1 Answered Questions

[SOLVED] The Definitive C++ Book Guide and List

  • 2008-12-23 05:23:56
  • grepsedawk
  • 2362071 View
  • 4243 Score
  • 1 Answer
  • Tags:   c++ c++-faq

28 Answered Questions

[SOLVED] How do you set, clear, and toggle a single bit?

23 Answered Questions

[SOLVED] When to use self over $this?

  • 2008-09-30 06:23:06
  • Casey Watson
  • 700437 View
  • 1997 Score
  • 23 Answer
  • Tags:   php class oop scope

15 Answered Questions

[SOLVED] What is the effect of extern "C" in C++?

9 Answered Questions

25 Answered Questions

[SOLVED] When should you use a class vs a struct in C++?

  • 2008-09-10 16:29:54
  • Alan Hinchcliffe
  • 402467 View
  • 949 Score
  • 25 Answer
  • Tags:   c++ oop class struct ooad

Sponsored Content