How to handle private class members in STL routines? [duplicate] - c++
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?
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.
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.
I found handy place to use friend access: Unittest of private functions.
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...
Friend comes handy when you are building a container and you want to implement an iterator for that class.
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:
Game
/ \
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.
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.
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 {
private:
friend class Fred;
FredBase() { }
};
class Fred : private virtual FredBase {
public:
...
};
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.
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 {
public:
friend bool equal(Beer a, Beer b);
private:
// ...
};
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 {
public:
friend Birds operator +(Birds, Birds);
private:
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!
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.
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.
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 {
public:
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
{
public:
Friender() {}
virtual ~Friender() {}
private:
// MSVC != GCC
#ifdef _MSC_VER
friend ToFriend;
#else
friend class FriendIdentity<ToFriend>::me;
#endif
};
/**
* 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.
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.
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.
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 :`(
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:
// 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;
}
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
{
public:
void need_your_data(B & myBuddy)
{
myBuddy.take_this_name(name_);
}
private:
string name_;
};
class B
{
public:
void print_buddy_name(A & myBuddy)
{
myBuddy.need_your_data(*this);
}
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.
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.
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.
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 http://www.cplusplus.com/doc/tutorial/inheritance/ .
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;
public:
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;
}
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.
This may not be an actual use case situation but may help to illustrate the use of friend between classes.
The ClubHouse
class ClubHouse {
public:
friend class VIPMember; // VIP Members Have Full Access To Class
private:
unsigned nonMembers_;
unsigned paidMembers_;
unsigned vipMembers;
std::vector<Member> members_;
public:
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 }
protected:
void joinVIPEvent( unsigned memberID ) { // ...code }
}; // ClubHouse
The Members Class's
class Member {
public:
enum MemberShipType {
NON_MEMBER_PAID_EVENT, // Single Event Paid (At Door)
PAID_MEMBERSHIP, // Monthly - Yearly Subscription
VIP_MEMBERSHIP, // Highest Possible Membership
}; // MemberShipType
protected:
MemberShipType type_;
unsigned id_;
Amenity amenity_;
public:
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 {
public:
explicit NonMember( unsigned id ) : Member( id, MemberShipType::NON_MEMBER_PAID_EVENT ) {}
void getAmenityFromClubHouse() override {
Amenity = ClubHouse::getAmenity( this->id_ );
}
};
class PaidMember : public Member {
public:
explicit PaidMember( unsigned id ) : Member( id, MemberShipType::PAID_MEMBERSHIP ) {}
void getAmenityFromClubHouse() override {
Amenity = ClubHouse::getAmenity( this->id_ );
}
};
class VIPMember : public Member {
public:
friend class ClubHouse;
public:
explicit VIPMember( unsigned id ) : Member( id, MemberShipType::VIP_MEMBERSHIP ) {}
void getAmenityFromClubHouse() override {
Amenity = ClubHouse::getAmenity( this->id_ );
}
void attendVIPEvent() {
ClubHouse::joinVIPEvent( this->id );
}
};
Amenities
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.
Seems I'm about 14 years late to the party. But here goes.
TLDR TLDR
Friend classes are there so that you can extend encapsulation to the group of classes which comprise your data structure.
TLDR
Your data structure in general consists of multiple classes. Similarly to a traditional class (supported by your programming language), your data structure is a generalized class which also has data and invariants on that data which spans across objects of multiple classes. Encapsulation protects those invariants against accidental modification of the data from the outside, so that the data-structure's operations ("member functions") work correctly. Friend classes extend encapsulation from classes to your generalized class.
The too long
A class is a datatype together with invariants which specify a subset of the values of the datatype, called the valid states. An object is a valid state of a class. A member function of a class moves a given object from a valid state to another.
It is essential that object data is not modified from outside of the class member functions, because this could break the class invariants (i.e. move the object to an invalid state). Encapsulation prohibits access to object data from outside of the class. This is an important safety feature of programming languages, because it makes it hard to inadvertedly break class invariants.
A class is often a natural choice for implementing a data structure, because the properties (e.g. performance) of a data structure is dependent on invariants on its data (e.g. red-black tree invariants). However, sometimes a single class is not enough to describe a data structure.
A data structure is any set of data, invariants, and functions which move that data from a valid state to another. This is a generalization of a class. The subtle difference is that the data may be scattered over datatypes rather than be concentrated on a single datatype.
Data structure example
A prototypical example of a data structure is a graph which is stored using separate objects for vertices (class Vertex), edges (class Edge), and the graph (class Graph). These classes do not make sense independently. The Graph class creates Vertexs and Edges by its member functions (e.g. graph.addVertex() and graph.addEdge(aVertex, bVertex)) and returns pointers (or similar) to them. Vertexs and Edges are similarly destroyed by their owning Graph (e.g. graph.removeVertex(vertex) and graph.removeEdge(edge)). The collection of Vertex objects, Edge objects and the Graph object together encode a mathematical graph. In this example the intention is that Vertex/Edge objects are not shared between Graph objects (other design choices are also possible).
A Graph object could store a list of all its vertices and edges, while each Vertex could store a pointer to its owning Graph. Hence, the Graph object represents the whole mathematical graph, and you would pass that around whenever the mathematical graph is needed.
Invariant example
An invariant for the graph data structure then would be that a Vertex is listed in its owner Graph's list. This invariant spans both the Vertex object and the Graph object. Multiple objects of multiple types can take part in a given invariant.
Encapsulation example
Similarly to a class, a data structure benefits from encapsulation which protects against accidental modification of its data. This is because the data structure needs to preserve invariants to be able to function in promised manner, exactly like a class.
In the graph data structure example, you would state that Vertex is a friend of Graph, and also make the constructors and data-members of Vertex private so that a Vertex can only be created and modified by Graph. In particular, Vertex would have a private constructor which accepts a pointer to its owning graph. This constructor is called in graph.addVertex(), which is possible because Vertex is a friend of Graph. (But note that Graph is not a friend of Vertex: there is no need for Vertex to be able to access Graph's vertex-list, say.)
Terminology
The definition of a data structure acts itself like a class. I propose that we start using the term 'generalized class' for any set of data, invariants, and functions which move that data from a valid state to another. A C++ class is then a specific kind of a generalized class. It is then self-evident that friend classes are the precise mechanism for extending encapsulation from C++ classes to generalized classes.
(In fact, I'd like the term 'class' to be replaced with the concept of 'generalized class', and use 'native class' for the special case of a class supported by the programming language. Then when teaching classes you would learn of both native classes and these generalized classes. But perhaps that would be confusing.)
Related
Why are private variables of a class accessible from an object in the class?
Let's say we have a class with a single private variable and a max method that takes a single parameter of the same type of the class: class A { private: int Number; public: A() : Number(0) {} A(int val) : Number(val) {} int max(A b) { if( Number > b.Number ) return Number; return b.Number; } }; What is strange to me is that the parameter b in the max method has access to the private variable Number. However in the main function we do not have access to the parameter Number (as expected since it is declared private) int main() { A a; a.Number = 0; // ERROR return 0; } So my question is why does the function in the class have access to the variable Number when it is declared private.
It's just the rule, that's all. It's designed to make member functions, especially functions like assignment operators, copy constructors, and overloaded operators, simpler to write. If you couldn't access the members of the "other" object directly then you'd need a plethora of friend declarations or ugly "getters"; the latter tend to offer little more than a circumvention of encapsulation. Perhaps the way you propose could have been the default, and to bring in the private and protected members and functions could have required the declaration friend class; But C++ was not designed this way, and that proposal would now be an hideous breaking change. Something to muse on though to recover your expected behaviour could be a declaration friend class = delete; which would, as far as I can tell, not be a breaking change. Why not propose something of this form to the ISO C++ Committee?
The principle idea behind encapsulation is to hide the internals of a class from external classes. When you consider that the function you're writing is internal to the class A, it makes sense for the function to be aware of A's internals - regardless of the context.
Why does C++ not allow inherited friendship?
Why is friendship not at least optionally inheritable in C++? I understand transitivity and reflexivity being forbidden for obvious reasons (I say this only to head off simple FAQ quote answers), but the lack of something along the lines of virtual friend class Foo; puzzles me. Does anyone know the historical background behind this decision? Was friendship really just a limited hack that has since found its way into a few obscure respectable uses? Edit for clarification: I'm talking about the following scenario, not where children of A are exposed to either B or to both B and its children. I can also imagine optionally granting access to overrides of friend functions, etc. class A { int x; friend class B; }; class B { // OK as per friend declaration above. void foo(A& a, int n) { a.x = n; } }; class D : public B { /* can't get in A w/o 'friend class D' declaration. */ }; Accepted answer: as Loki states, the effect can be simulated more or less by making protected proxy functions in friended base classes, so there is no strict need for granting friendship to a class or virtual method heirarchy. I dislike the need for boilerplate proxies (which the friended base effectively becomes), but I suppose that this was deemed preferable over a language mechanism that would more likely be misused most of the time. I think it's probably time I bought and read Stroupstrup's The Design and Evolution of C++, which I've seen enough people here recommend, to get better insight to these types of questions ...
Because I may write Foo and its friend Bar (thus there is a trust relationship). But do I trust the people who write classes that are derived from Bar? Not really. So they should not inherit friendship. Any change in the internal representation of a class will require a modification to anything that is dependent on that representation. Thus all members of a class and also all friends of the class will require modification. Therefore if the internal representation of Foo is modified then Bar must also be modified (because friendship tightly binds Bar to Foo). If friendship was inherited then all class derived from Bar would also be tightly bound to Foo and thus require modification if Foo's internal representation is changed. But I have no knowledge of derived types (nor should I. They may even be developed by different companies etc). Thus I would be unable to change Foo as doing so would introduce breaking changes into the code base (as I could not modify all class derived from Bar). Thus if friendship was inherited you are inadvertently introducing a restriction on the ability to modify a class. This is undesirable as you basically render useless the concept of a public API. Note: A child of Bar can access Foo by using Bar, just make the method in Bar protected. Then the child of Bar can access a Foo by calling through its parent class. Is this what you want? class A { int x; friend class B; }; class B { protected: // Now children of B can access foo void foo(A& a, int n) { a.x = n; } }; class D : public B { public: foo(A& a, int n) { B::foo(a, n + 5); } };
A friended class may expose its friend through accessor functions, and then grant access through those. class stingy { int pennies; friend class hot_girl; }; class hot_girl { public: stingy *bf; int &get_cash( stingy &x = *bf ) { return x.pennies; } }; class moocher { public: // moocher can access stingy's pennies despite not being a friend int &get_cash( hot_girl &x ) { return x.get_cash(); } }; This allows finer control than optional transitivity. For example, get_cash may be protected or may enforce a protocol of runtime-limited access.
C++ Standard, section 11.4/8 Friendship is neither inherited nor transitive. If friendship would be inherited, then a class that wasn't meant to be a friend would suddenly have access to your class internals and that violates encapsulation.
Because it's just unnecessary. The usage of the friend keyword is itself suspicious. In term of coupling it's the worst relationship (way ahead of inheritance and composition). Any change to the internals of a class have a risk to impact the friends of this class... do you really want an unknown number of friends ? You would not even be able to list them if those who inherit from them could be friends also, and you would run in the risk of breaking your clients code each time, surely this is not desirable. I freely admit that for homework/pet projects dependency is often a far away consideration. On small size projects it doesn't matter. But as soon as several persons work on the same project and this grows into the dozens of thousands of lines you need to limit the impact of changes. This bring a very simple rule: Changing the internals of a class should only affect the class itself Of course, you'll probably affect its friends, but there are two cases here: friend free function: probably more of a member function anyway (I am think std::ostream& operator<<(...) here, which is not a member purely by accident of the language rules friend class ? you don't need friend classes on real classes. I would recommend the use of the simple method: class Example; class ExampleKey { friend class Example; ExampleKey(); }; class Restricted { public: void forExampleOnly(int,int,ExampleKey const&); }; This simple Key pattern allows you to declare a friend (in a way) without actually giving it access to your internals, thus isolating it from changes. Furthermore it allows this friend to lend its key to trustees (like children) if required.
A guess: If a class declares some other class/function as a friend, it's because that second entity needs privileged access to the first. What use is there in granting the second entity privileged access to an arbitrary number of classes derived from the first?
A derived class can inherit only something, which is 'member' of the base. A friend declaration is not a member of the befriending class. $11.4/1- "...The name of a friend is not in the scope of the class, and the friend is not called with the member access operators (5.2.5) unless it is a member of another class." $11.4 - "Also, because the base-clause of the friend class is not part of its member declarations, the base-clause of the friend class cannot access the names of the private and protected members from the class granting friendship." and further $10.3/7- "[Note: the virtual specifier implies membership, so a virtual function cannot be a nonmember (7.1.2) function. Nor can a virtual function be a static member, since a virtual function call relies on a specific object for determining which function to invoke. A virtual function declared in one class can be declared a friend in another class. ]" Since the 'friend' is not a member of the base class in the first place, how can it be inherited by the derived class?
Friend function in a class assigns the extern property to the function. i.e. extern means that the function has been declared and defined somewhere out of the class. Hence it means friend function is not a member of a class. So the inheritance only allows you to inherit the properties of a class not external things. And also if inheritance is allowed for friend functions, then a third party class inheriting.
Friend is good in inheritance like style interface for container But for me, as the first say, C++ lack the propagatable inheritance class Thing; //an interface for Thing container's struct IThing { friend Thing; protected: int IThing_getData() = 0; }; //container for thing's struct MyContainer : public IThing { protected: //here is reserved access to Thing int IThing_getData() override {...} }; struct Thing { void setYourContainer(IThing* aContainerOfThings) { //access to unique function in protected area aContainerOfThings->IThing_getData(); //authorized access } }; struct ChildThing : public Thing { void doTest() { //here the lack of granularity, you cannot access to the container. //to use the container, you must implement all //function in the Thing class aContainerOfThings->IThing_getData(); //forbidden access } }; For me the problem of C++ is the lack of very good granularity to control all access from anywhere for anything : friend Thing can become friend Thing.* to grant access to all child of Thing And more, friend [named area] Thing.* to grant access for a precise are in the Container class via special named area for the friend. Ok stop the dream. But now, you know an interesting usage of friend. In another order, you can also found interesting to known all class are friendly with self. In other word, a class instance can call all members of another instance of same name without restriction: class Object { private: void test() {} protected: void callAnotherTest(Object* anotherObject) { //private, but yes you can call test() from //another object instance anotherObject)->test(); } };
Simple logic : 'I have a friend Jane. Just because we became friends yesterday does not make all of her friends mine.' I still need to approve those individual friendships, and the level of trust would be accordingly.
Good design mechanism for exposing class internals to future predicate functors?
I have a class Widget with some private internals, but I would like to expose these internals to predicate functors (only) via friendship. class Widget { ComponentA a; ComponentB b; friend class WidgetPredicate; }; class WidgetPredicate : public std::unary_function<bool, const Widget&> { bool operator () (const Widget& w) const { // inspect a and b and make a yes/no decision } }; The intent is that I can use the WidgetPredicate function as a sifter in all the std::xxxx_if family of algorithms. However, I would like to leave some extensibility in the system where a future developer could make new predicates that somehow inheirit the friend status neatly. Is there a good design idiom for this? My current (non) solution is that everything in Widget is public. I tried toying around with a base class that exposed the internals of Widget to subtypes of WidgetPredicate through protected functions, something like: class WidgetPredicate : public std::unary ... { protected: const ComponentA& expose_a ( const Widget& w ) const { return w.a; } const ComponentB& expose_b ( const Widget& w ) const { return w.b; } public: virtual bool operator () ... }; class DerivedWidgetPredicate : public WidgetPredicate { public: virtual bool operator () (const Widget& w) { const ComponentA& a = this->expose_a(w); // a can now be inspected/predicated upon const ComponentB& b = this->expose_b(w); // b ... } }; I can live with the potential that now any class could examine Widget's internals just by saying :public WidgetPredicate. I am not trying to protect against malicious developers, so if they say they're a friendly WidgetPredicate then I am willing to take that at face value. The syntax is also subpar, but I can live with that too. What I don't like the maintainence issue, that when I change the internals of Widget I have to also add new expose() methods to the base predicate. (IMO That process could and should be mechanical). I could always put the expose methods directly in the Widget class, but IMO at that point I might as well make the fields public and just live with it (ie my current soln).
While it is more expensive, you should define what operations can be allowed for external code and implement them. If you do not want to offer those operations in your public/protected interface, the solution you have posted (declaring another class as a friend and using it as a proxy into your internal code) is a fine solution. This is subjective, and probably an unwanted comment, but anyway... There is no such thing as a good design mechanism for exposing class internals. < irony>Just make everything public < /irony> What you are doing is developing a complex mechanism to break your encapsulation. After you are done with it, all code can access your private members. You state that only predicate functors will have access to the members, but you cannot block non-predicate classes from deriving from the predicate type just to acquire access to the data. One of the points of encapsulation is reducing dependencies: external code only depend on the public interface, you can always change your internal types and representation and external code will not break (external as not class or friend code). Now, after you have exposed (directly or indirectly) your internals, then those are now part of your public interface and must thus be frozen. Another point of encapsulation is that you can guarantee invariants on the internal data. After external code have access to the internals, there is no way you can control any kind of invariant on your methods (say keeping the max_size field of a container to the size of the acquired memory) and your class can break due to others misuse. There are reasons for friendship not being transitive nor inherited: when you declare a class to be a friend of your class, you can check the behavior of that class (and in most cases you are in full control of the friend class). You know that the code you are giving access to does not break your own code. class Widget { friend class BackDoor; // assume that you have implemented it }; class MaliciousClass1 // third class, malicious or not cannot break into Widget { }; class MaliciousClass2 : public BackDoor // You cannot block external code from deriving from BackDoor { // Can break into your widget, access and modify anything }; The door is open for any and everyone to play with your private parts.
When should I use C++ private inheritance?
Unlike protected inheritance, C++ private inheritance found its way into mainstream C++ development. However, I still haven't found a good use for it. When do you guys use it?
I use it all the time. A few examples off the top of my head: When I want to expose some but not all of a base class's interface. Public inheritance would be a lie, as Liskov substitutability is broken, whereas composition would mean writing a bunch of forwarding functions. When I want to derive from a concrete class without a virtual destructor. Public inheritance would invite clients to delete through a pointer-to-base, invoking undefined behaviour. A typical example is deriving privately from an STL container: class MyVector : private vector<int> { public: // Using declarations expose the few functions my clients need // without a load of forwarding functions. using vector<int>::push_back; // etc... }; When implementing the Adapter Pattern, inheriting privately from the Adapted class saves having to forward to an enclosed instance. To implement a private interface. This comes up often with the Observer Pattern. Typically my Observer class, MyClass say, subscribes itself with some Subject. Then, only MyClass needs to do the MyClass -> Observer conversion. The rest of the system doesn't need to know about it, so private inheritance is indicated.
Note after answer acceptance: This is NOT a complete answer. Read other answers like here (conceptually) and here (both theoretic and practic) if you are interested in the question. This is just a fancy trick that can be achieved with private inheritance. While it is fancy it is not the answer to the question. Besides the basic usage of just private inheritance shown in the C++ FAQ (linked in other's comments) you can use a combination of private and virtual inheritance to seal a class (in .NET terminology) or to make a class final (in Java terminology). This is not a common use, but anyway I found it interesting: class ClassSealer { private: friend class Sealed; ClassSealer() {} }; class Sealed : private virtual ClassSealer { // ... }; class FailsToDerive : public Sealed { // Cannot be instantiated }; Sealed can be instantiated. It derives from ClassSealer and can call the private constructor directly as it is a friend. FailsToDerive won't compile as it must call the ClassSealer constructor directly (virtual inheritance requirement), but it cannot as it is private in the Sealed class and in this case FailsToDerive is not a friend of ClassSealer. EDIT It was mentioned in the comments that this could not be made generic at the time using CRTP. The C++11 standard removes that limitation by providing a different syntax to befriend template arguments: template <typename T> class Seal { friend T; // not: friend class T!!! Seal() {} }; class Sealed : private virtual Seal<Sealed> // ... Of course this is all moot, since C++11 provides a final contextual keyword for exactly this purpose: class Sealed final // ...
The canonical usage of private inheritance is the "implemented in terms of" relationship (thanks to Scott Meyers' 'Effective C++' for this wording). In other words, the external interface of the inheriting class has no (visible) relationship to the inherited class, but it uses it internally to implement its functionality.
One useful use of private inheritence is when you have a class that implements an interface, that is then registered with some other object. You make that interface private so that the class itself has to register and only the specific object that its registered with can use those functions. For example: class FooInterface { public: virtual void DoSomething() = 0; }; class FooUser { public: bool RegisterFooInterface(FooInterface* aInterface); }; class FooImplementer : private FooInterface { public: explicit FooImplementer(FooUser& aUser) { aUser.RegisterFooInterface(this); } private: virtual void DoSomething() { ... } }; Therefore the FooUser class can call the private methods of FooImplementer through the FooInterface interface, while other external classes cannot. This is a great pattern for handling specific callbacks that are defined as interfaces.
I think the critical section from the C++ FAQ Lite is: A legitimate, long-term use for private inheritance is when you want to build a class Fred that uses code in a class Wilma, and the code from class Wilma needs to invoke member functions from your new class, Fred. In this case, Fred calls non-virtuals in Wilma, and Wilma calls (usually pure virtuals) in itself, which are overridden by Fred. This would be much harder to do with composition. If in doubt, you should prefer composition over private inheritance.
I find it useful for interfaces (viz. abstract classes) that I'm inheriting where I don't want other code to touch the interface (only the inheriting class). [edited in an example] Take the example linked to above. Saying that [...] class Wilma needs to invoke member functions from your new class, Fred. is to say that Wilma is requiring Fred to be able to invoke certain member functions, or, rather it is saying that Wilma is an interface. Hence, as mentioned in the example private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code. comments on the desired effect of programmers needing to meet our interface requirements, or breaking the code. And, since fredCallsWilma() is protected only friends and derived classes can touch it i.e. an inherited interface (abstract class) that only the inheriting class can touch (and friends). [edited in another example] This page briefly discusses private interfaces (from yet another angle).
Sometimes I find it useful to use private inheritance when I want to expose a smaller interface (e.g. a collection) in the interface of another, where the collection implementation requires access to the state of the exposing class, in a similar manner to inner classes in Java. class BigClass; struct SomeCollection { iterator begin(); iterator end(); }; class BigClass : private SomeCollection { friend struct SomeCollection; SomeCollection &GetThings() { return *this; } }; Then if SomeCollection needs to access BigClass, it can static_cast<BigClass *>(this). No need to have an extra data member taking up space.
Private Inheritance to be used when relation is not "is a", But New class can be "implemented in term of existing class" or new class "work like" existing class. example from "C++ coding standards by Andrei Alexandrescu, Herb Sutter" :- Consider that two classes Square and Rectangle each have virtual functions for setting their height and width. Then Square cannot correctly inherit from Rectangle, because code that uses a modifiable Rectangle will assume that SetWidth does not change the height (whether Rectangle explicitly documents that contract or not), whereas Square::SetWidth cannot preserve that contract and its own squareness invariant at the same time. But Rectangle cannot correctly inherit from Square either, if clients of Square assume for example that a Square's area is its width squared, or if they rely on some other property that doesn't hold for Rectangles. A square "is-a" rectangle (mathematically) but a Square is not a Rectangle (behaviorally). Consequently, instead of "is-a," we prefer to say "works-like-a" (or, if you prefer, "usable-as-a") to make the description less prone to misunderstanding.
I found a nice application for private inheritance, although it has a limited usage. Problem to solve Suppose you are given the following C API: #ifdef __cplusplus extern "C" { #endif typedef struct { /* raw owning pointer, it's C after all */ char const * name; /* more variables that need resources * ... */ } Widget; Widget const * loadWidget(); void freeWidget(Widget const * widget); #ifdef __cplusplus } // end of extern "C" #endif Now your job is to implement this API using C++. C-ish approach Of course we could choose a C-ish implementation style like so: Widget const * loadWidget() { auto result = std::make_unique<Widget>(); result->name = strdup("The Widget name"); // More similar assignments here return result.release(); } void freeWidget(Widget const * const widget) { free(result->name); // More similar manual freeing of resources delete widget; } But there are several disadvantages: Manual resource (e.g. memory) management It is easy to set up the struct wrong It is easy to forget freeing the resources when freeing the struct It is C-ish C++ Approach We are allowed to use C++, so why not use its full powers? Introducing automated resource management The above problems are basically all tied to the manual resource management. The solution that comes to mind is to inherit from Widget and add a resource managing instance to the derived class WidgetImpl for each variable: class WidgetImpl : public Widget { public: // Added bonus, Widget's members get default initialized WidgetImpl() : Widget() {} void setName(std::string newName) { m_nameResource = std::move(newName); name = m_nameResource.c_str(); } // More similar setters to follow private: std::string m_nameResource; }; This simplifies the implementation to the following: Widget const * loadWidget() { auto result = std::make_unique<WidgetImpl>(); result->setName("The Widget name"); // More similar setters here return result.release(); } void freeWidget(Widget const * const widget) { // No virtual destructor in the base class, thus static_cast must be used delete static_cast<WidgetImpl const *>(widget); } Like this we remedied all the above problems. But a client can still forget about the setters of WidgetImpl and assign to the Widget members directly. Private inheritance enters the stage To encapsulate the Widget members we use private inheritance. Sadly we now need two extra functions to cast between both classes: class WidgetImpl : private Widget { public: WidgetImpl() : Widget() {} void setName(std::string newName) { m_nameResource = std::move(newName); name = m_nameResource.c_str(); } // More similar setters to follow Widget const * toWidget() const { return static_cast<Widget const *>(this); } static void deleteWidget(Widget const * const widget) { delete static_cast<WidgetImpl const *>(widget); } private: std::string m_nameResource; }; This makes the following adaptions necessary: Widget const * loadWidget() { auto widgetImpl = std::make_unique<WidgetImpl>(); widgetImpl->setName("The Widget name"); // More similar setters here auto const result = widgetImpl->toWidget(); widgetImpl.release(); return result; } void freeWidget(Widget const * const widget) { WidgetImpl::deleteWidget(widget); } This solution solves all the problems. No manual memory management and Widget is nicely encapsulated so that WidgetImpl does not have any public data members anymore. It makes the implementation easy to use correctly and hard (impossible?) to use wrong. The code snippets form a compiling example on Coliru.
If you need a std::ostream with some small changes (like in this question) you may need to Create a class MyStreambuf which derives from std::streambuf and implement changes there Create a class MyOStream which derives from std::ostream that also initializes and manages an instance of MyStreambuf and passes the pointer to that instance to the constructor of std::ostream The first idea might be to add the MyStream instance as a data member to the MyOStream class: class MyOStream : public std::ostream { public: MyOStream() : std::basic_ostream{ &m_buf } , m_buf{} {} private: MyStreambuf m_buf; }; But base classes are constructed before any data members so you are passing a pointer to a not yet constructed std::streambuf instance to std::ostream which is undefined behavior. The solution is proposed in Ben's answer to the aforementioned question, simply inherit from the stream buffer first, then from the stream and then initialize the stream with this: class MyOStream : public MyStreamBuf, public std::ostream { public: MyOStream() : MyStreamBuf{} , basic_ostream{ this } {} }; However the resulting class could also be used as a std::streambuf instance which is usually undesired. Switching to private inheritance solves this problem: class MyOStream : private MyStreamBuf, public std::ostream { public: MyOStream() : MyStreamBuf{} , basic_ostream{ this } {} };
If derived class - needs to reuse code and - you can't change base class and - is protecting its methods using base's members under a lock. then you should use private inheritance, otherwise you have danger of unlocked base methods exported via this derived class.
Sometimes it could be an alternative to aggregation, for example if you want aggregation but with changed behaviour of aggregable entity (overriding the virtual functions). But you're right, it has not many examples from the real world.
A class holds an invariant. The invariant is established by the constructor. However, in many situations it's useful to have a view of the representation state of the object (which you can transmit over network or save to a file - DTO if you prefer). REST is best done in terms of an AggregateType. This is especially true if you're const correct. Consider: struct QuadraticEquationState { const double a; const double b; const double c; // named ctors so aggregate construction is available, // which is the default usage pattern // add your favourite ctors - throwing, try, cps static QuadraticEquationState read(std::istream& is); static std::optional<QuadraticEquationState> try_read(std::istream& is); template<typename Then, typename Else> static std::common_type< decltype(std::declval<Then>()(std::declval<QuadraticEquationState>()), decltype(std::declval<Else>()())>::type // this is just then(qes) or els(qes) if_read(std::istream& is, Then then, Else els); }; // this works with QuadraticEquation as well by default std::ostream& operator<<(std::ostream& os, const QuadraticEquationState& qes); // no operator>> as we're const correct. // we _might_ (not necessarily want) operator>> for optional<qes> std::istream& operator>>(std::istream& is, std::optional<QuadraticEquationState>); struct QuadraticEquationCache { mutable std::optional<double> determinant_cache; mutable std::optional<double> x1_cache; mutable std::optional<double> x2_cache; mutable std::optional<double> sum_of_x12_cache; }; class QuadraticEquation : public QuadraticEquationState, // private if base is non-const private QuadraticEquationCache { public: QuadraticEquation(QuadraticEquationState); // in general, might throw QuadraticEquation(const double a, const double b, const double c); QuadraticEquation(const std::string& str); QuadraticEquation(const ExpressionTree& str); // might throw } At this point, you might just store collections of cache in containers and look it up on construction. Handy if there's some real processing. Note that cache is part of the QE: operations defined on the QE might mean the cache is partially reusable (e.g., c does not affect the sum); yet, when there's no cache, it's worth to look it up. Private inheritance can almost always modelled by a member (storing reference to the base if needed). It's just not always worth it to model that way; sometimes inheritance is the most efficient representation.
Just because C++ has a feature, doesn't mean it's useful or that it should be used. I'd say you shouldn't use it at all. If you're using it anyway, well, you're basically violating encapsulation, and lowering cohesion. You're putting data in one class, and adding methods that manipulates the data in another one. Like other C++ features, it can be used to achieve side effects such as sealing a class (as mentioned in dribeas' answer), but this doesn't make it a good feature.
When should you use 'friend' in C++?
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?
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.
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.
I found handy place to use friend access: Unittest of private functions.
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...
Friend comes handy when you are building a container and you want to implement an iterator for that class.
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: Game / \ 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.
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.
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 { private: friend class Fred; FredBase() { } }; class Fred : private virtual FredBase { public: ... };
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.
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 { public: friend bool equal(Beer a, Beer b); private: // ... }; 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 { public: friend Birds operator +(Birds, Birds); private: 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!
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.
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.
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 { public: 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 { public: Friender() {} virtual ~Friender() {} private: // MSVC != GCC #ifdef _MSC_VER friend ToFriend; #else friend class FriendIdentity<ToFriend>::me; #endif }; /** * 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.
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.
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.
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 :`(
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: // 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; }
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 { public: void need_your_data(B & myBuddy) { myBuddy.take_this_name(name_); } private: string name_; }; class B { public: void print_buddy_name(A & myBuddy) { myBuddy.need_your_data(*this); } 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.
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.
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.
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 http://www.cplusplus.com/doc/tutorial/inheritance/ . 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; public: 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; }
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.
This may not be an actual use case situation but may help to illustrate the use of friend between classes. The ClubHouse class ClubHouse { public: friend class VIPMember; // VIP Members Have Full Access To Class private: unsigned nonMembers_; unsigned paidMembers_; unsigned vipMembers; std::vector<Member> members_; public: 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 } protected: void joinVIPEvent( unsigned memberID ) { // ...code } }; // ClubHouse The Members Class's class Member { public: enum MemberShipType { NON_MEMBER_PAID_EVENT, // Single Event Paid (At Door) PAID_MEMBERSHIP, // Monthly - Yearly Subscription VIP_MEMBERSHIP, // Highest Possible Membership }; // MemberShipType protected: MemberShipType type_; unsigned id_; Amenity amenity_; public: 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 { public: explicit NonMember( unsigned id ) : Member( id, MemberShipType::NON_MEMBER_PAID_EVENT ) {} void getAmenityFromClubHouse() override { Amenity = ClubHouse::getAmenity( this->id_ ); } }; class PaidMember : public Member { public: explicit PaidMember( unsigned id ) : Member( id, MemberShipType::PAID_MEMBERSHIP ) {} void getAmenityFromClubHouse() override { Amenity = ClubHouse::getAmenity( this->id_ ); } }; class VIPMember : public Member { public: friend class ClubHouse; public: explicit VIPMember( unsigned id ) : Member( id, MemberShipType::VIP_MEMBERSHIP ) {} void getAmenityFromClubHouse() override { Amenity = ClubHouse::getAmenity( this->id_ ); } void attendVIPEvent() { ClubHouse::joinVIPEvent( this->id ); } }; Amenities 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.
Seems I'm about 14 years late to the party. But here goes. TLDR TLDR Friend classes are there so that you can extend encapsulation to the group of classes which comprise your data structure. TLDR Your data structure in general consists of multiple classes. Similarly to a traditional class (supported by your programming language), your data structure is a generalized class which also has data and invariants on that data which spans across objects of multiple classes. Encapsulation protects those invariants against accidental modification of the data from the outside, so that the data-structure's operations ("member functions") work correctly. Friend classes extend encapsulation from classes to your generalized class. The too long A class is a datatype together with invariants which specify a subset of the values of the datatype, called the valid states. An object is a valid state of a class. A member function of a class moves a given object from a valid state to another. It is essential that object data is not modified from outside of the class member functions, because this could break the class invariants (i.e. move the object to an invalid state). Encapsulation prohibits access to object data from outside of the class. This is an important safety feature of programming languages, because it makes it hard to inadvertedly break class invariants. A class is often a natural choice for implementing a data structure, because the properties (e.g. performance) of a data structure is dependent on invariants on its data (e.g. red-black tree invariants). However, sometimes a single class is not enough to describe a data structure. A data structure is any set of data, invariants, and functions which move that data from a valid state to another. This is a generalization of a class. The subtle difference is that the data may be scattered over datatypes rather than be concentrated on a single datatype. Data structure example A prototypical example of a data structure is a graph which is stored using separate objects for vertices (class Vertex), edges (class Edge), and the graph (class Graph). These classes do not make sense independently. The Graph class creates Vertexs and Edges by its member functions (e.g. graph.addVertex() and graph.addEdge(aVertex, bVertex)) and returns pointers (or similar) to them. Vertexs and Edges are similarly destroyed by their owning Graph (e.g. graph.removeVertex(vertex) and graph.removeEdge(edge)). The collection of Vertex objects, Edge objects and the Graph object together encode a mathematical graph. In this example the intention is that Vertex/Edge objects are not shared between Graph objects (other design choices are also possible). A Graph object could store a list of all its vertices and edges, while each Vertex could store a pointer to its owning Graph. Hence, the Graph object represents the whole mathematical graph, and you would pass that around whenever the mathematical graph is needed. Invariant example An invariant for the graph data structure then would be that a Vertex is listed in its owner Graph's list. This invariant spans both the Vertex object and the Graph object. Multiple objects of multiple types can take part in a given invariant. Encapsulation example Similarly to a class, a data structure benefits from encapsulation which protects against accidental modification of its data. This is because the data structure needs to preserve invariants to be able to function in promised manner, exactly like a class. In the graph data structure example, you would state that Vertex is a friend of Graph, and also make the constructors and data-members of Vertex private so that a Vertex can only be created and modified by Graph. In particular, Vertex would have a private constructor which accepts a pointer to its owning graph. This constructor is called in graph.addVertex(), which is possible because Vertex is a friend of Graph. (But note that Graph is not a friend of Vertex: there is no need for Vertex to be able to access Graph's vertex-list, say.) Terminology The definition of a data structure acts itself like a class. I propose that we start using the term 'generalized class' for any set of data, invariants, and functions which move that data from a valid state to another. A C++ class is then a specific kind of a generalized class. It is then self-evident that friend classes are the precise mechanism for extending encapsulation from C++ classes to generalized classes. (In fact, I'd like the term 'class' to be replaced with the concept of 'generalized class', and use 'native class' for the special case of a class supported by the programming language. Then when teaching classes you would learn of both native classes and these generalized classes. But perhaps that would be confusing.)