4

How do I do forward referencing / declaration in C++ to avoid circular header file references?

I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how.

H H
  • 263,252
  • 30
  • 330
  • 514
CVertex
  • 17,997
  • 28
  • 94
  • 124

3 Answers3

15

You predeclare the class without including it. For example:

//#include "Foo.h" // including Foo.h causes circular reference
class Foo;

class Bar
{
...
};
antik
  • 5,282
  • 1
  • 34
  • 47
  • Also to note in this case: class Bar cannot contain a class Foo, but it can have a pointer to a class Foo. – KPexEA Oct 08 '08 at 18:12
  • Also note that the formal return type of functions can be of the forward declared type. – QBziZ Oct 08 '08 at 18:14
1

I believe the correct term for what you are talking about is "forward declaration". "Forward referencing" would be a bit confusing.

Dima
  • 38,860
  • 14
  • 75
  • 115
-2

You won't get circular header files references if you have #ifndef guards. That's the point.

Forward referencing is used to avoid #include(ing) header files for objects you use only by pointer or reference. However, in this case you are not solving a circular reference problem, you're just practicing good design and decoupling the .h file from details it doesn't need to know.

Joe Schneider
  • 9,179
  • 7
  • 42
  • 59
  • That's not accurate. forward referencing could replace the need for an #include and thus eliminating the need for an #include circle. – shoosh Oct 08 '08 at 17:50
  • 2
    I agree that if you didn't have #ifndef guards, you might (sloppily) try to manage all your circular header dependencies by using forward declarations, however the OP said he DID have header guards. – Joe Schneider Oct 09 '08 at 00:07