Search code examples
c++classpointerscircular-dependencyincomplete-type

How to make classes using each other


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?


Solution

  • 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);
    }