friend class/function in c++ [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should you use 'friend' in C++?
I see a lot of people recommending a function/class to be made a friend of another class here in SO though there are other alternatives. Shouldn't friend be sparingly used in C++? I feel other options must be considered before deciding on using the friend feature. Opinions/suggestions are welcome.

Some say friend is a violation of encapsulation. In my opinion, it is the exact contrary. Without friend, we would end up with either:
huge monolithic classes, that does plenty of things they were not meant to, just to avoid letting outer classes access their internals
badly encapsulated classes: to separate concerns and write classes with one and only one responsability, we would need to provide public access to internal data needed by the related set of classes.
friend is a good way to overcome this issue, since it lets you free to separate responsabilities in several classes, while at the same time letting you restrict access to implementation details to the few functions or types which need them.

I agree. The friend keyword should be used sparingly.
It may be useful if you have a set of classes that interact together when you want to expose a clean api from those classes to users, but when the classes can interact with each other using a richer interface.
Eg:
class Folder
{
public:
int GetFileCount();
private:
void IncrementFileCount(); // users of this class have no right to use this
friend class File;
};
class File
{
public:
File(string name, Folder& containingFolder)
{
containingFolder.IncrementFileCount(); // except for indirectly when they create a file
}
};

Without specific examples this is hard to decide. While friend isn't strictly necessary it does have its uses. If, as you claim, there are better alternatives then obviously use them, by simple definition of the word “better”. Or maybe the decision which solution is better isn't that clean-cut after all.
Personally, I prefer to avoid it when possible but I prefer to use it over method duplication: for example, I do not like to write a print method just to avoid making operator << a friend because I don't see the benefit of the duplicate method.

For all those who thinks friend violates the encapsulation, here is what Bjarne Stroustup has to say .
But I personally don't use friend unless it is inevitable. Scenarios like implementation of Iterator patterns there is no other choice.
Friend is friend if used properly otherwise he is enemy!

Friend functions are advantageous in cases where you would want to call a 3rd party library function which needs access to members of your class, consider for example:
class A {
private:
int x,y;
double result;
public:
friend void *power(void *x);
}
You can now call the pow function found in math.h using this friend function.Your power function can now be defined as:
void *power(void *X)
{
A *a;
a = static_cast< A *> (X);
a->result = pow(a->x,a->y);
return NULL;
}
Although there are easier ways of calling the pow function.This example is only meant to illustrate the importance of friend function in calling library functions.
Hope it is useful.

Related

Friend Class In C++

here im not understanding the concept very well or i am right.... So lets take this "friend" class example here:
class MyClass{
friend class AnotherClass;
private:
int secret;
}
class AnotherClass{
public:
void getSecret(MyClass mc){
return mc.secret;
}
}
So Yes... in the above code it will actually work if you do it... but in general, why cant you use getters and setters all the time instead of friend class? Is the reason of friend class usage because of "tediousness"?
friend is for when you don't want to expose getters/setters/internals to everyone, but just to a single class. So it's a tool for encapsulation.
For example, if you provided a public getSecret in MyClass, everyone could have access to that private variable even if they shouldn't know about it. This breaks encapsulation. friend is there to fix this problem, so that only those classes that need to know about secret have access to it.
As #nicomp said, "it's like giving your physical friend a key to your house but you don't know what they will do with it". So a friend class has unlimited access to all internals of the class it's friends with. This in unfortunate, but the key (no pun intended) here is to keep classes as small as possible so that this doesn't become a problem, which also would be according to the Single Responsibility Principle.
A public getter or setter permits anybody access. They have some uses, notably for maintaining class invariants when some property is changed, but a getter / setter pair that look like the following code are no better than public member variables for constraining access:
class A {
public:
int getX() const { return x; };
void setX(int x_) { x = x_; };
private:
int x;
};
The getX() and setX() functions do nothing but provide access to x. Everybody can use them, so anybody can change the value of x. There's no point making it private, then.
If, instead, only some classes or functions need to be able to change x, you can make them friends of class A. This restricts the access to only those friends, rather than giving it to everybody.
As such, friend is a tool for encapsulation, permitting the encapsulation to be wider than "just my own class" (private members) or "just my class and classes that derive from it" (protected members). A friend need not be in the same class hierarchy (it need not be a class at all; functions can be friends), but it still permits you to restrict access to only those things that actually need it.
Note that, like getters and setters, it should be used sparingly. Encapsulation is a good thing, and where possible the private members of your class should remain just that – private. friend is a tool that allows you to selectively grant access, but you should always carefully consider whether that access needs to be granted, or whether the function / class that needs it would be better off as a member of your class, instead.
Don't forget about testing and/or copying...
Friend classes / methods can be used quite successfully for checking intermediate states within class functionality.
They can also be useful for some types of copy constructors, where the class to be copied is not a direct ancestor of the target class thus precluding protected members as an option.
Consider the following use-case that I encountered recently: I refactored some code from one class into another class. This new class had to access members from the original class but I did not want to provide this via public getters to avoid other clients messing around with these. In this case, I really welcomed the C++-friendship mechanism.
However, these use cases are very seldom (hopefully, otherwise there is probably something wrong in your SW architecture) and I try to avoid it as much as I can since it is the tightest form of coupling.

Can two classes friend each other?

I haven't yet worked out a specific case. But I am about to embark on writing some code that I feel will end up needing this; and so I wanted to know if:
Two classes can friend each other; so that they can freely access the private
and protected members of the other (I believe the answer is yes, and ofcourse I
can simply try it out!). Any detailed references or other question links with answers
are also very welcome. I am aware of forward declarations and include guard compiler
pre-directives and their use. My questions are rather more related to the semantics
of the C++ language in terms of what it can offer with regard to this possibility
of mutual friendship and how to use it properly.
Is this generally recommended? Do people employ this kind of design on a regular basis?
Under what circumstances would this be a recommended design (preferably with some
examples).
You can have mutual friendship:
class A {
friend class B;
};
class B {
friend class A;
};
Whether or not this makes sense depends entirely on the problem you are trying to solve. It definitely could make sense in certain circumstances.
The only example from my current project that utilizes mutual friendship is a container implementation: the container class is a friend of its iterator class and vice versa.

Is this key-oriented access-protection pattern a known idiom?

Matthieu M. brought up a pattern for access-protection in this answer that i'd seen before, but never conciously considered a pattern:
class SomeKey {
friend class Foo;
SomeKey() {}
// possibly make it non-copyable too
};
class Bar {
public:
void protectedMethod(SomeKey);
};
Here only a friend of the key class has access to protectedMethod():
class Foo {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // fine, Foo is friend of SomeKey
}
};
class Baz {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // error, SomeKey::SomeKey() is private
}
};
It allows more fine-granular access-control than making Foo a friend of Bar and avoids more complicated proxying patterns.
Does anyone know whether this approach already has a name, i.e., is a known pattern?
Thanks to your other question it looks like this pattern is now known as the "passkey" pattern.
In C++11, it gets even cleaner, because instead of calling
b.protectedMethod(SomeKey());
you can just call:
b.protectedMethod({});
It seems that this idiom like one mentioned in another SO question here. It is called Attorney-Client idiom and described in more details there.
some boring man like me would make the fowllow code:
int FraudKey=0;
b.protectedMethod(reinterpret_cast<SomeKey&>(FraudKey));
Its pretty close to this:
http://minorfs.wordpress.com/2013/01/18/raiicap-pattern-injected-singleton-alternative-for-c/
Basically if you consider a reference to an object of well designed class to be provide the
access control you need to implement any access control policy that actually makes sense, applying this pattern to anything other than the constructor does not seem to make that much sense.
So as the article states, if you use this key in conjunction with those constructors for what
access control might make sense, objects that represent significant parts of scares resources, that in C++ would generally be implemented as RAII objects, than the name RAIICap or RAII-Capability would indeed make sense.
http://www.eros-os.org/essays/capintro.html
Alternatively you could refer to it with a more general name like construct authority.
The implementation in the article is a bit to much main centered, that is, main needs to create all the authority keys. You can extend on it and make it more flexible by adding an additional public constructor for the key itself:
template <typename T>
class construct_authority {
public:
construct_authority(construct_authority<void> const&)
friend int main(int,char **);
private:
construct_authority(){}
};
That way main could delegate the key creation to other parts of the program.
Personally I think the RAIICap name is quite appropriate for the useful part of this pattern.
A while ago I proposed that this simple template above could be added to the standard library.
https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/p_v-aYIvO1E
Unfortunately there are issues with the idea that there can be one main fingerprint that constitutes a computational root, so something like this apparently can't have a place in the standard library. Having said this, at least for the use with the constructor of RAII classes, this pattern seems to be quite useful.

Member functions for derived information in a class

While designing an interface for a class I normally get caught in two minds whether should I provide member functions which can be calculated / derived by using combinations of other member functions. For example:
class DocContainer
{
public:
Doc* getDoc(int index) const;
bool isDocSelected(Doc*) const;
int getDocCount() const;
//Should this method be here???
//This method returns the selected documents in the contrainer (in selectedDocs_out)
void getSelectedDocs(std::vector<Doc*>& selectedDocs_out) const;
};
Should I provide this as a class member function or probably a namespace where I can define this method? Which one is preferred?
In general, you should probably prefer free functions. Think about it from an OOP perspective.
If the function does not need access to any private members, then why should it be given access to them? That's not good for encapsulation. It means more code that may potentially fail when the internals of the class is modified.
It also limits the possible amount of code reuse.
If you wrote the function as something like this:
template <typename T>
bool getSelectedDocs(T& container, std::vector<Doc*>&);
Then the same implementation of getSelectedDocs will work for any class that exposes the required functions, not just your DocContainer.
Of course, if you don't like templates, an interface could be used, and then it'd still work for any class that implemented this interface.
On the other hand, if it is a member function, then it'll only work for this particular class (and possibly derived classes).
The C++ standard library follows the same approach. Consider std::find, for example, which is made a free function for this precise reason. It doesn't need to know the internals of the class it's searching in. It just needs some implementation that fulfills its requirements. Which means that the same find() implementation can work on any container, in the standard library or elsewhere.
Scott Meyers argues for the same thing.
If you don't like it cluttering up your main namespace, you can of course put it into a separate namespace with functionality for this particular class.
I think its fine to have getSelectedDocs as a member function. It's a perfectly reasonable operation for a DocContainer, so makes sense as a member. Member functions should be there to make the class useful. They don't need to satisfy some sort of minimality requirement.
One disadvantage to moving it outside the class is that people will have to look in two places when the try to figure out how to use a DocContainer: they need to look in the class and also in the utility namespace.
The STL has basically aimed for small interfaces, so in your case, if and only if getSelectedDocs can be implemented more efficiently than a combination of isDocSelected and getDoc it would be implemented as a member function.
This technique may not be applicable anywhere but it's a good rule of thumbs to prevent clutter in interfaces.
I agree with the answers from Konrad and jalf. Unless there is a significant benefit from having "getSelectedDocs" then it clutters the interface of DocContainer.
Adding this member triggers my smelly code sensor. DocContainer is obviously a container so why not use iterators to scan over individual documents?
class DocContainer
{
public:
iterator begin ();
iterator end ();
// ...
bool isDocSelected (Doc *) const;
};
Then, use a functor that creates the vector of documents as it needs to:
typedef std::vector <Doc*> DocVector;
class IsDocSelected {
public:
IsDocSelected (DocContainer const & docs, DocVector & results)
: docs (docs)
, results (results)
{}
void operator()(Doc & doc) const
{
if (docs.isDocSelected (&doc))
{
results.push_back (&doc);
}
}
private:
DocContainer const & docs;
DocVector & results;
};
void foo (DocContainer & docs)
{
DocVector results;
std :: for_each (docs.begin ()
, docs.end ()
, IsDocSelected (docs, results));
}
This is a bit more verbose (at least until we have lambdas), but an advantage to this kind of approach is that the specific type of filtering is not coupled with the DocContainer class. In the future, if you need a new list of documents that are "NotSelected" there is no need to change the interface to DocContainer, you just write a new "IsDocNotSelected" class.
The answer is proabably "it depends"...
If the class is part of a public interface to a library that will be used by many different callers then there's a good argument for providing a multitude of functionality to make it easy to use, including some duplication and/or crossover. However, if the class is only being used by a single upstream caller then it probably doesn't make sense to provide multiple ways to achieve the same thing. Remember that all the code in the interface has to be tested and documented, so there is always a cost to adding that one last bit of functionality.
I think this is perfectly valid if the method:
fits in the class responsibilities
is not too specific to a small part of the class clients (like at least 20%)
This is especially true if the method contains complex logic/computation that would be more expensive to maintain in many places than only in the class.

When to use friend class in C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should you use 'friend' in C++?
I was brushing up on my C++ (I'm a Java developer) and I came across the friend class keyword which I had forgotten about for a while. Is this one of those features that's just part of the kitchen sink, or is there a good reason for doing this rather than just a vanilla getter? I understand the difference in that it limits who can access the data, but I can't think of a scenario when this would be necessary.
Note: I've seen a similar question, but specifically I'm asking, is this just an advanced feature that adds no real value except to confuse people looking at you're code until they realize what you're doing?
I agree with the comments that say the friend keyword can improve encapsulation if used wisely. I'd just add that the most common (legitimate!) use for friend classes may be testing. You may want a tester class to have a greater degree of access than other client classes would have. A tester class could have a good reason to look at internal details that are deliberately hidden from other classes.
In my experience, the cases when friend (or mutable, which is a little similar) to actually enhance encapsulation of data are rare compared with how often it's used to break encapsulation.
It's rarely useful to me but when I do use it it's for cases in which I've had to split a class that was formerly a single class into two separate classes that need to access some common data/functionality.
Edit to respond to Outlaw Programmer's comment: We absolutely agree on this. One other option apart from friend'ing classes after splitting them is to make public accessors, which sometimes break encapsulation! I think that some people think that friendly classes somehow breaks encapsulation because they've seen it used improperly a lot, and many people probably never see code where it's been used correctly, because it's a rare thing. I like your way of stating it though - friendliness is a good middle ground between not allowing you to split up your class and making EVERYTHING accessible to the public.
Edit to respond to David Thornley: I agree that the flexibility that C++ allows you to do things like this is a result of the design decisions that went into C++. I think that's what it makes it even more important to understand what things are generally good and bad style in flexible languages. Java's perspective is that you should never have friend classes so that these aren't provided, but as C++ programmers it's our responsibility as a community to define appropriate use of these very flexible but sometimes misused language constructs.
Edit to respond to Tom: Mutable doesn't necessarily break encapsulation, but many of the uses of the mutable keyword that I've seen in real-life situations break encapsulation, because it's much more common to see people breaking encapsulation with mutable than to actually find and understand a proper use of mutable in the first place.
When you wish that one class (Factory) be responsible for creating instances of another class (Type). You can make the constructor of the Type private and thus make sure that only the Factory can create Type objects. It is useful when you wish to delegate the checks to some other class which could serve as a validator.
Just one usage scenario.
P.S. Really missing the "friend" keyword in C#...
A concrete instance would be a class factory, where you want one class to only be created through another factory class, so you make the constructors private, and the factory class a friend of the produced class.
It's kinda' like a 2" 12-point 3/4"-drive socket - not terribly common, but when you need it, you're awfully glad you have it.
Helps with Memento design pattern
The FAQ's section about friends: here
The FQA's section about friends: here
Two different points of view about friend.
I look at the friend construct as one of those features of the language that should be used in rare occasions, but that doesn't make it useless. There are several patterns that call for making friend classes, many of them already on this site in that "Related" bar on the right. ====>
Friendship is used when you have multiple classes and/or functions that work together to provide the same abstraction or interface. The classic example is implementing some kind of numerical class, and all the non-member operator functions (*, -, +, <<, etc) are given friendship so that they can work on the private data of the numerical class.
Such use cases are somewhat rare, but they do exist, and friend is very useful.
Here is one example, of several, I'm sure, where a friend class can be legitimately used without disregarding the reasons for encapsulation.
MyClass inherits from GeneralClass. MyClass has gotten big, so you created HelperClass to encapsulate some of the function of MyClass. However, HelperClass needs access to some protected functions in GeneralClass to properly perform it's function, so you make HelperClass a friend to MyClass.
This is better than exposing the protected functions, because they don't need to be available to everybody, but it helps keep your code organized in an OOP way to keep MyClass from getting too complex. It makes sense, because although HelperClass isn't concretely related to MyClass by inheritance, it does have some sort of logical connection to it, embodied in the code, and in design, as "friend".
I always ( and only ) use friend for unit testing private methods. The only other way I can imagine to do this would be to load up the public interface with a whole lot of testing methods, which is just too messy and so I prefer to hide the test methods in a seperate test class.
Something like this:
class cMyClassTest;
class cMyClass
{
public:
.....
private:
friend cMyClassTest;
int calc(); // tricky algorithm, test carefully
};
class cMyClassTest
{
public:
int test_calc()
{
cMyClass test;
....
int result = test.calc();
if( result == 42 )
return 1;
return 0;
}
};
friend class mean we all know that is acesss the value of variable from other class so it is mainly used for use the values so we no need to return the value of other class to main function then main to needed class member function but it having the problem that is a class is friend for other class then friend class should be in below of that class