Friend Functions
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

Friend Functions

A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and –>) unless they are 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. It is not affected by the access control keywords.

The following example shows a Point class and a friend function, ChangePrivate. The friend function has access to the private data member of the Point object it receives as a parameter.

// friend_functions.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
class Point
    friend void ChangePrivate( Point & );
    Point( void ) : m_i(0) {}
    void PrintPrivate( void ){cout << m_i << endl; }

    int m_i;

void ChangePrivate ( Point &i ) { i.m_i++; }

int main()
   Point sPoint;


© 2015 Microsoft