Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: member access into incomplete type : forward declaration of

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 ?

like image 825
LOLKFC Avatar asked Nov 13 '13 19:11

LOLKFC


2 Answers

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();
}
like image 110
masoud Avatar answered Nov 07 '22 21:11

masoud


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();
}
like image 15
Some programmer dude Avatar answered Nov 07 '22 23:11

Some programmer dude