C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers


10,705 users

What are advantages/disadvantages of using friends in c++?

+1 vote
asked Nov 22, 2010 by anonymous
edited Dec 14, 2010 by pa

1 Answer

+1 vote
Best answer
 using friends is generally syntactic. Ie: both a member fn
and a friend are equally privileged

a friend function can be called like f(obj), where a member is called like obj.f().

friends are used when two or more classes are designed to be more tightly coupled than you want for.

they add to the global namespace. In contrast, the namespace of member functions is buried within the class, reducing the chance for namespace collisions for functions.

They aren't inherited. That is, the `friendship privilege' isn't inherited. This is actually an advantage when it comes to encapsulation. Ex: I may declare you as my friend, but that doesn't mean I trust your kids.

they don't bind dynamically. Ie: they don't respond to polymorphism. There are no virtual friends; if you need one, have a friend call a hidden (usually `protected:') virtual member fn. Friends that take a ptr/ref to a class can also take a ptr/ref to a publically derived class object, so they act as if they are inherited, but the friendship *rights* are not inherited
answered Nov 22, 2010 by anonymous

Related questions

0 votes
1 answer 70 views
70 views asked Jan 8, 2014 by keem Expert (13,240 points)
0 votes
1 answer 245 views
0 votes
1 answer 65 views
0 votes
1 answer 133 views
0 votes
1 answer 321 views