Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placement of friend declarations

Does it matter where in a class a friend clause is placed (i.e. within the protected block as opposed to the private block)?

like image 571
Qix - MONICA WAS MISTREATED Avatar asked Sep 27 '12 12:09

Qix - MONICA WAS MISTREATED


People also ask

Where do I put my friend's class declaration?

Friends aren't in the class's scope, and they aren't called using the member-selection operators (. and ->) unless they're members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration.

Does friend need forward declaration?

We can declare both a member function and a free function as a friend in the class body. For a free function, it is very straightforward and a forward declaration is not required. We can simply declare the friend as follows: The void Print(const Test& test) function has access to the private members of the Test class.

How do you declare a friend function?

Declaration of a friend function in C++class class_name { friend data_type function_name(arguments/s); //syntax of friend function. }; In the above declaration, the keyword friend precedes the function. We can define the friend function anywhere in the program like a normal C++ function.

Are friend functions public or private?

The friend function can be a member of another class or a function that is outside the scope of the class. A friend function can be declared in the private or public part of a class without changing its meaning. Friend functions are not called using objects of the class because they are not within the class's scope.


1 Answers

No it does not.

class X
{
public:
    friend class A;
private:
    friend class B;
protected:
    friend class C;
};

All three classes are now friends of X and share the exact same priviliges.

A good convention is to group all friend declarations together for visibility, but that's just style.

11.4 Friends

9) A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration. The meaning of the friend declaration is the same whether the friend declaration appears in the private, protected or public (9.2) portion of the class member-specification.

like image 50
Luchian Grigore Avatar answered Oct 13 '22 23:10

Luchian Grigore