C ++ circular header includes

I know that similar questions have been asked before, but after doing my research, I still have questions about the circular heading.

//FooA.h
#ifndef H_FOOA
#define H_FOOA

#include "foob.h"

class FooA{
   public:
      FooB *fooB;
};


//FooB.h
#ifndef H_FOOB
#define H_FOOB

class FooA;
class FooB{
   public:
      FooA *fooA;
};

Now, if I have two round dependencies, this is the way I saw people on stackoverflow to get around the problem. My only problem is that in my main.cpp I have to enable fooa.h first and then foob.h

//main.cpp the right way
#include "fooa.h"
#include "foob.h"

//main.cpp that will surely get a compile error
#include "foob.h"
#include "fooa.h"

Now my question is: "Is there a way to forward declare these classes so that I can not worry about the order in which I include the header files in my main.cpp?"

+5
source share
4 answers

, , main.cpp?

, :

FooA.h

#ifndef H_FOOA
#define H_FOOA

// #include "foob.h" << not needed!
class FooB;       // << substitute with a forward declaration of FooB

class FooA{
   public:
      FooB *fooB;
};
#endif

FooB.h

#ifndef H_FOOB
#define H_FOOB

class FooA;
class FooB{
   public:
      FooA *fooA;
};
#endif
+7

, fooa.h foob.h, foob.h FooA. .

+2

, . .

, , , , cpp.

+1
source

Use forward declaration in both header files.

Do you know that you can declare it in one line?

In "FooB.h"

class FooB{
    public:
        class FooA *fooA;
};

In "FooA.h"

class FooA {
    public:
        class FooB *fooB;
};
+1
source

All Articles