0

I have two classes A and B, where I would like to access the private members of B from A.

class A; // Forward declaration    

class B {
    friend class A; // A is a friend of B

    A a; // error: 'B::a' uses undefined class 'A'
private:
    int i;
};

class A {

public:
    B *m_b;

    A(B *i_b) : m_b(i_b) {}; // legal access due to friendship
};

However, I do not understand why I get the following error: 'B::a' uses undefined class 'A'

evolved
  • 1,850
  • 19
  • 40
  • 4
    `A` is an *incomplete type* at that point, so the compiler doesn't know its size. – Fred Larson Feb 28 '18 at 17:10
  • A should be forward-declared and defined before B. Then it'll work. – Richard Hodges Feb 28 '18 at 17:11
  • 1
    Revert your classes order and make forward declaration of the class B instead of A. – 273K Feb 28 '18 at 17:11
  • You cannot store a concrete instance of `A` without knowing its definition (and therefore its size). Flip your declarations around and forward declare `B`, since you can store a pointer to `B` without needing the whole class definition. – 0x5453 Feb 28 '18 at 17:11
  • You can't declare `A a` after a forward declaration alone: the type must be completely defined to be used like that. – Sergey Kalinichenko Feb 28 '18 at 17:12
  • 2
    It's not clear why you need `friend class A;` Nothing in `A` is accessing the `private` parts of `B`. – R Sahu Feb 28 '18 at 17:15

0 Answers0