Forward declarations of classes :S

Started by
9 comments, last by SeraphLance 9 years, 3 months ago

Standard FAQ for inclusion in C (and mostly applicable to C++):

I have a function void foo(bar* b); in foo.c that needs stuff in bar.c!

In foo.c, include bar.h. In foo.h, forward declare bar. Do it like so:

C:


//C:
typedef struct bar bar;

//C++:
class bar; //or struct bar;

I have a function void foo(bar b); in foo.c that needs stuff in bar.c!

No you don't. Seriously, don't.

Okay, you really need to do this? Are you sure?

Okay. Then include bar.h in foo.h consider factoring bar.c into a separate .h file that only contains the struct data, and include that file in both bar.c and foo.h. If you neglect to do this, then don't come crying to anyone when you start to see bizarre bugs (premature hint: You probably have some weird #define in some windows header).

Why would I do that when I can just #include "bar.h" in foo.h

Because transitive dependencies make subsequent programmers very, very angry, and some of them have guns.

This topic is closed to new replies.

Advertisement