forwarding declaration

Started by
3 comments, last by nilkn 18 years, 7 months ago

// A.h file
class A
{
B * b;
b->fun();
public:
//stuff
}

// B.h
class B
{
A * a;
public:
a->fun();
//stuff
}

how to solve the problem. forwarding declaration not work.
Advertisement
A* a;a->fun();


The above requires the definition of A to be available. What is usually done is only keep the A* a; part in the header file, and move the second line to a source file. This way, you can use a forward declaration to make the header self-sustaining, and include all definitions in the source file to make it compile.
So ,if the 2 class can not be changed, no solution is available??
Well, obviously, if you can't change the code, the problem will not be solved.
The compiler does not need the full class declaration to make a pointer to it.

Therefore, you can solve your cyclical dependency like so:

// In ClassA.h:// Use a forward declaration to tell the compiler B is a typeclass B;class A {     B* b;};// In ClassA.cpp:#include "ClassA.h"#include "ClassB.h"// somewhere later on...b->fun();

This topic is closed to new replies.

Advertisement