Suppose I want something of this sort, in one .cpp
source file:
class A {
public:
void doSomething(B *b) {};
};
class B {
public:
void doSomething(A *a) {};
};
Is there anyway of doing this without splitting it into two separate files, and without receiving a compiler error (syntax error on doSomething(B *b)
)
put at the first line:
class B;
If I remember well, you can 'pre-declare' your class B.
class B; // predeclaration of class B
class A
{
public:
void doSomething(B* b);
}
class B
{
public
void doSomething(A* a) {}
}
public void A::doSomething(B* b) {}
Then, your class 'A' knows that a class 'B' will exists, although it hasn't been really defined yet.
Forward declaration is indeed the correct term, as mentionned by Evan Teran in the comments.
forward declare one class before other with
class B;
or
class A;
But still you won't be able to implement
void doSomething(B *b)
using only forward declaration of B. So you have to put definition of doSomething below full class A declaration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With