-1
class A;
class B;

class A
{   
public:
    A(B * b) : b(b)
    {   
        b->foo(this);
    }   
private:
    B * b;
};  

class B
{   
public:
    void foo(A *)
    {}  
};

Compiling this code gives me

incomplete-type.hpp: In constructor ‘A::A(B*)’:
incomplete-type.hpp:9:4: error: invalid use of incomplete type ‘class B’
   b->foo(this);
    ^~

But I really need the classes to use each other via pointers. How can I do this?

  • 2
    Define the constructor outside the class definition and after both classes have been defined. – wally Nov 10 '16 at 20:50

1 Answers1

3

Move the function definitions that actually use the other type to below, where both types are complete.

class A;
class B;

class A
{   
public:
    A(B * b);
private:
    B * b;
};  

class B
{   
public:
    void foo(A *)
    {}  
};

inline A::A(B * b) : b(b)
{
    b->foo(this);
}
aschepler
  • 70,891
  • 9
  • 107
  • 161