Export (0) Print
Expand All

Friend Functions and Nested Classes

Friend functions declared in a nested class are considered to be in the scope of the nested class, not the enclosing class. Therefore, the friend functions gain no special access privileges to members or member functions of the enclosing class. If you want to use a name that is declared in a nested class in a friend function and the friend function is defined in file scope, use qualified type names as follows:

// friend_functions_and_nested_classes.cpp

#include <string.h>

    sizeOfMessage = 255

char *rgszMessage[sizeOfMessage];

class BufferedIO
    class BufferedInput
        friend int GetExtendedErrorStatus();
        static char *message;
        static int  messageSize;
        int iMsgNo;

char *BufferedIO::BufferedInput::message;
int BufferedIO::BufferedInput::messageSize;

int GetExtendedErrorStatus()
    int iMsgNo = 1; // assign arbitrary value as message number

    strcpy_s( BufferedIO::BufferedInput::message,
              rgszMessage[iMsgNo] );

    return iMsgNo;

int main()

The following code shows the function GetExtendedErrorStatus declared as a friend function. In the function, which is defined in file scope, a message is copied from a static array into a class member. Note that a better implementation of GetExtendedErrorStatus is to declare it as:

int GetExtendedErrorStatus( char *message )

With the preceding interface, several classes can use the services of this function by passing a memory location where they want the error message copied.

Community Additions

© 2014 Microsoft