0

I'm trying to access a private member of a class from a friend function, but I keep getting an error about x being a private class of B.

I know a particular solution may be to just friend the function inside B, but I would like a more generic solution, in case I need more friend functions in A that need access to B but don't want to explicitly friend them in B.

#include <iostream>

using namespace std;

class B {
private:
    int x = 10;
    friend class A;
};

class A  {
private:
    B b;
public:
    friend ostream& operator<< (ostream&, A&);
};

ostream& operator<< (ostream& out, A& a){
    out << a.b.x << endl;
    return out;
}

int main() {
    A a;
    cout << a;
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    Like with humans, A is a friend of B and C is a friend of A does not mean C is a friend of B. Declare the explicit friendship B and C. – 273K May 17 '21 at 20:37
  • 1
    Or delegate to A getting b.x: `int A::getBx() const { return b.x; }`. `out << a.b.x << endl;` --> `out << a.getBx() << endl;`. – 273K May 17 '21 at 20:46
  • A friend of your friend is not always your friend, too. – Sam Varshavchik May 17 '21 at 20:48
  • I see, but can you please explain the results I am getting from the following code: `https://pastebin.com/raw/wnPX3BdD` It is the same code with a useless template around each class but it seems to do the trick I cannot explain why – LukeTheWalker May 17 '21 at 21:09
  • About your template comment - this is worth reading: https://stackoverflow.com/questions/424104/can-i-access-private-members-from-outside-the-class-without-using-friends https://stackoverflow.com/questions/15110526/allowing-access-to-private-members https://www.worldcadaccess.com/blog/2020/05/how-to-hack-c-with-templates-and-friends.html – Jerry Jeremiah May 17 '21 at 21:43

0 Answers0