Search code examples
c++friend

Multiple level friendship


In code below:

class B {
    int x;
    int y;
};

class A {
    friend class Other;
    friend class A;
    int a;
     B* b;
public:
    A(){ b = new B();}
};

struct Other {
    A a;
    void foo() {
        std::cout << a.b->x;  // error
    }
};

int main() {
    Other oth;
    oth.foo();
}

The indicated line fails with:

t.cpp:22:19: error: 'x' is a private member of 'B'
std::cout << a.b->x;
                  ^
t.cpp:7:5: note: implicitly declared private here
int x; 

Why friendship is not working when referring from class member to other class member?


Solution

  • This line:

    std::cout << a.b->x;
    

    involves accessing a private member of A (b) and a private member of B (x) within class Other. While A gave access privileges to Other, B did not, hence the error. If you want this to work, you'll need to add:

    class B {
        friend class Other;
    };
    

    Side-note, this declaration is meaningless:

    class A {
        friend class A;
    };
    

    A class already has access to its own private members. So calling it its own friend is redundant.