Question

I have two classes in the same .cpp file:

// forward
class B;

class A {       
   void doSomething(B * b) {
      b->add();
   }
};

class B {
   void add() {
      ...
   }
};

The forward does not work, I cannot compile.

I get this error:

error: member access into incomplete type 'B'
note: forward declaration of 'B'

I'm using clang compiler (clang-500.2.79).

I don't want to use multiple files (.cpp and .hh), I'd like to code just on one .cpp.

I cannot write the class B before the class A.

Do you have any idea of how to resolve my problem ?

Was it helpful?

Solution

Move doSomething definition outside of its class declaration and after B and also make add accessible to A by public-ing it or friend-ing it.

class B;

class A
{
    void doSomething(B * b);
};

class B
{
public:
    void add() {}
};

void A::doSomething(B * b)
{
    b->add();
}

OTHER TIPS

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top