Export (0) Print
Expand All
3 out of 17 rated this helpful - Rate this topic

Friend Declarations

If you declare a friend function that was not previously declared, that function is exported to the enclosing nonclass scope.

Functions declared in a friend declaration are treated as if they had been declared using the extern keyword. (For more information about extern, see Static Storage-Class Specifiers.)

Although functions with global scope can be declared as friends prior to their prototypes, member functions cannot be declared as friends before the appearance of their complete class declaration. The following code shows why this fails:

class ForwardDeclared;   // Class name is known.
class HasFriends
{
    friend int ForwardDeclared::IsAFriend();   // C2039 error expected
};

The preceding example enters the class name ForwardDeclared into scope, but the complete declaration — specifically, the portion that declares the function IsAFriend — is not known. Therefore, the friend declaration in class HasFriends generates an error.

To declare two classes that are friends of one another, the entire second class must be specified as a friend of the first class. The reason for this restriction is that the compiler has enough information to declare individual friend functions only at the point where the second class is declared.

NoteNote

Although the entire second class must be a friend to the first class, you can select which functions in the first class will be friends of the second class.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.