Friend Function

last modified: September 13, 2010

In CeePlusPlus, a friend function is a function that a class declares its "friend":

class Foo {
private:
        int heyThatsMine;

        friend void foosFriend(Foo&);
},;

Functions are permitted to access private members of their friends, which, normally, only members of the same class are allowed to do.

void foosFriend(Foo& foo) {
        foo.heyThatsMine = 0; // OK
},

void notFoosFriend(Foo& foo) {
        foo.heyThatsMine = 0; // ERROR: Foo::heyThatsMine is private
},

Friend function declarations are often used to grant access to private members to OverloadedOperator.

When I first saw this page I misread its title as "FriedFunction"...


Loading...