Archived

This topic is now archived and is closed to further replies.

doogle

Circular Classes

Recommended Posts

I thought I had this worked out...
//foo.h
#include "bar.h"

class Foo
{
public:
   Foo();
   Foo(Bar* b);

   Bar *b;
};
 
//bar.h
#include "foo.h"

class Bar
{
public:
   Bar();
   
   Foo *f;
};
 
Why does this sort of thing get me so many errors??

Share this post


Link to post
Share on other sites
i think you have to use what''s called a forward declaration on one of the classes. for class Bar, you have to have a line that says class Foo; then in class Foo, you can go ahead and include bar.h

a2k

Share this post


Link to post
Share on other sites
bar.h includes foo.h and foo.h includes bar.h thus creating circular headache for the linker. Use forward reference that introduces the name bar to foo like so:

//foo.h

// Forward reference
class bar;

// class Foo
class Foo
{
public:
Foo();
Foo(Bar* b);
Bar *b;
};

"bar" class type is partially defined here so the linker knows about it. Notice the bar.h was taken out in foo.h file. Include foo.h before any other headers in foo.cpp file and use pointers or references exclusively if you can to prevent this circularity. Now you can include foo.h inside bar.h file just fine in this scenario since foo.h doesn''t include "bar.h" header anymore.

Check out www.BruceEckel.com website for a free C++ book that explains this and other scenarios(singleton, etc). It''s very good book for intermediate programmers since the book is more than learning c++ syntax. If you have msvc++6 check out msdn library''s c++ language book also(could be found online at ms too at www.msdn.microsoft.com but am not sure). It goes into technicality more. I use it more than the c++ standard I bought because it is written toward users of c++ while the standard targets compiler writers I think.

Share this post


Link to post
Share on other sites
quote:
Original post by JD
Sorry a2k, didn''t see your post when I submitted mine.


np. alternate and more thorough sources are always good for solidifying the common solution.

Share this post


Link to post
Share on other sites