56
votes

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 ?

2
Move the function body of A::doSomething after the definition of class B.dyp
I speak about that in the thread : "I cannot write the class B before the class A.". I use a example code to explain my problem. In my real code, I have a pointer to my class B in my class A. So, if I write the class B before the class A, the problem would be the same !LOLKFC
Names beginning with an underscore, such as _b, should be avoided. They can be used by the compiler/standard library in the global namespace; additionally, you should never use identifiers beginning with an underscore followed by an uppercase letter, such as _B (also reserved).dyp

2 Answers

45
votes

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();
}
12
votes

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