1

I have a problem. In the following example, there is a static private member variable called private_b of class A inside namespace a. And then I'm trying to access that variable from class B, which I have declared to be a friend of class A, but it doesn't work, with a compile error from GCC:

error: ‘B* a::A::private_b’ is private within this context

class B; namespace a { class A { private: static B* private_b; friend class B; }; B* A::private_b = nullptr; } class B { public: void foo() { B* foo = a::A::private_b; // Error here } }; 

I don't understand why I can't access it, and how to get around this problem. I really want class A to be inside that namespace, and class B doesn't make sense to be inside that namespace. I searched for this on the internet, but couldn't find this exact case, or couldn't find a solution for this case.

2
  • Violating encapsulation is a drastic design decision Commented Mar 5, 2022 at 21:09
  • Well, in my case class A and B are somewhat related and they are in the same cpp file in my library code. They are both used by the user code. Some data being private to user code but public in library code is not bad design, it is necessary IMO. Commented Mar 5, 2022 at 21:17

1 Answer 1

3

friend class B; declared friendship with B in the same namespace a. You may want friend class ::B;.

Note, friend class B; does not refer to the global forward declaration class B, it has own forward declaration class B after the keyword friend.

Sign up to request clarification or add additional context in comments.

2 Comments

Or just friend B; (with the forward declaration)
Wow... I would have never solved this problem on my own. But the solution makes total sense. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.