Search code examples
c++friendfriend-function

friend member function can't access private member data


I try to access a private member data of class X, with a friend function, which itself is a member function of class A.
Here's the code:

class X {
    int foo;
public:
    friend void A::func(X x1);
};

class A {
public:
    void func(X x1) { x1.foo = 999; }
};

This won't compile for the reason:
Error C2248 'X::foo': cannot access private member declared in class 'X'

I tried changing the order, declaring A before X, but it didn't help..
What's causing this?


Solution

  • There's another error that you're ignoring. Namely:

    error: 'A' has not been declared

    You'll need to declare the class A with the function before you can reference it in X as a friend. However, the function takes an X, so you also need to declare X first!

    It should look like:

    class X;
    
    class A {
    public:
        void func(X x1);
    };
    
    class X {
        int foo;
    public:
        friend void A::func(X x1);
    };
    
    void A::func(X x1) { x1.foo = 999; }