Skip to content

Last updated:2026-10-12

C++ friend

About the Author

WeChat official account:

wechat

0. Overview

friend provides a mechanism for an ordinary function or a class member function to access the private or protected members of another class. That is to say, there are two forms of friend:

(1)Friend function: an ordinary function accesses the private or protected members of some class.

(2)Friend class: member functions of class A access the private or protected members of class B

Advantage: improves the running efficiency of the program.

Disadvantage: breaks the encapsulation of the class and the transparency of the data.

Summary: - Can access private members - Breaks encapsulation - Friendship is not transitive - Friendship is one-way - The form and number of friend declarations are not restricted

1. Friend Functions

Declared in any region of the class declaration, while the definition is outside the class.

friend <类型><友元函数名>(<参数表>);

Note that a friend function is just an ordinary function, not a member function of the class; it can be called from anywhere, and inside the friend function the private or protected members of the class are accessed via the object name.

See the concrete code at: friend_func.cpp

#include <iostream>

using namespace std;

class A
{
public:
    A(int _a):a(_a){};
    friend int geta(A &ca);  ///< 友元函数
private:
    int a;
};

int geta(A &ca) 
{
    return ca.a;
}

int main()
{
    A a(3);    
    cout<<geta(a)<<endl;

    return 0;
}

2. Friend Classes

The friend class is declared inside the class's declaration and implemented outside the class.

friend class <友元类名>;

If class B is a friend of class A, then class B can directly access A's private members.

See the concrete code at: friend_class.cpp

#include <iostream>

using namespace std;

class A
{
public:
    A(int _a):a(_a){};
    friend class B;
private:
    int a;
};

class B
{
public:
    int getb(A ca) {
        return  ca.a; 
    };
};

int main() 
{
    A a(3);
    B b;
    cout<<b.getb(a)<<endl;
    return 0;
}

3. Notes

  • Friendship is not inherited If class B is a friend of class A, and class C derives from class A, then friend class B has no way to directly access the private or protected members of class C.

  • Friendship is not transitive If class B is a friend of class A, and class C is a friend of class B, then friend class C has no way to directly access the private or protected members of class A; that is, no such thing as a "friend of a friend" relationship exists.

Comments