Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, does adding a friend to a class change its memory layout?

Also, does it matter where in the class you declare the friend ? Does it matter if you add a friend class or a friend function ?

like image 351
Naveen Avatar asked Jun 23 '10 20:06

Naveen


People also ask

What happens when a class is declared as friend of another class?

Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class. For example, a LinkedList class may be allowed to access private members of Node.

Which of the following is true about friend functions in C?

Which of the following is correct about friend functions? Explanation: Friend function can be declared either in private or public part of the class. A friend function cannot access the members of the class directly. They use the dot membership operator with a member name.

What are the roles of friend function in a class?

Friend functions of the class are granted permission to access private and protected members of the class in C++. They are defined globally outside the class scope. Friend functions are not member functions of the class.

Does friend break encapsulation?

A friend function in the class declaration doesn't violate encapsulation any more than a public member function violates encapsulation: both have exactly the same authority with respect to accessing the class's non-public parts.)


2 Answers

No it doesn't. It's a purely compile-time thing: similar to access modifiers themselves.

Despite the fact that you write the declaration inside the class, you don't really add a friend to a class. You'd basically declare something else as a friend of the class and simply allow it to access the class's private members, as if they were public.

like image 146
mmx Avatar answered Sep 21 '22 00:09

mmx


As mentioned already, it is purely a compile-time mechanism.

like image 24
stinky472 Avatar answered Sep 22 '22 00:09

stinky472