Advertisement Jump to content
Sign in to follow this  
luasitdown

forwarding declaration

This topic is 4896 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

// 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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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 type
class B;

class A {

B* b;
};

// In ClassA.cpp:

#include "ClassA.h"
#include "ClassB.h"

// somewhere later on...
b->fun();

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!