1

Lets suppose we have a class A, which will include another class B as an element;

//ClasA.h
#ifndef _A_HEADER
#define _A_HEADER
#include "ClassB.h"
class B;
class A
{
private:
    B b;
public:
    A();
};
#endif

and

//ClassA.cpp
#include "ClassA.h"
A::A(){}

Now, we want class B to have a pointer to class A. So we define class B as:

//ClassB.h
#ifndef _B_HEADER
#define _B_HEADER
#include "ClassA.h"
class A;
class B
{
private:
    A *a;
public:
    B();
};
#endif

and

//ClassB.cpp
#include "ClassB.h"
B::B(){}

This way, we would have a class A, which would contain an object B. And The object B would have a pointer back to class A . Unfortunately, this do not work. I get the following error:

-ClassA.h:9:7: error: field ‘b’ has incomplete type. B b;

How can i fix this? And, considering that i fix it, is it worth it to implement a system like this? I mean, it surely doesn't feel very elegant.

-

user2864740
  • 60,010
  • 15
  • 145
  • 220
Victor Chavauty
  • 186
  • 3
  • 12
  • Use a forward declaration, and include in the translation units. Nothing generally wrong with the approach. – πάντα ῥεῖ Sep 09 '14 at 00:10
  • 1
    An assorted selection: http://stackoverflow.com/questions/10162580/mutually-dependent-class-declarations , http://stackoverflow.com/questions/21535239/c-mutual-class-dependency , http://stackoverflow.com/questions/3901606/proper-way-to-include-when-there-is-a-circular-dependency – user2864740 Sep 09 '14 at 00:12
  • Revisit your design, it's broken. – Captain Obvlious Sep 09 '14 at 00:14

1 Answers1

2

You're going to have to use a forward declaration on at least one class.

For example:

//ClassB.h
#ifndef _B_HEADER
#define _B_HEADER
class A;
class B
{
private:
    A *a;
public:
    B();
};
#include "ClassA.h"
#endif

And, considering that i fix it, is it worth it to implement a system like this?

There is typically nothing wrong with this approach, and sometimes it will be necessary.

In regards to the specific error you're seeing:

-ClassA.h:9:7: error: field ‘b’ has incomplete type. B b;

That is because, you can't declare anything implementation specific when using forward declarations. If you were using B *b;, you would probably get the error mentioned in the questions referenced in the comments.

mstrthealias
  • 2,781
  • 2
  • 22
  • 18