C++ forward reference

I have two C++ classes, Foo and Bar. Foo is defined in Foo.h and Foo.cc, and Bar is defined in Bar.h and Bar.cc.

Foo is a container for many instances of Bar. Instance methods of Foo return references to instances of Bar. Foo also does some low-level manipulation of Bar's member variables.

However, I have a reference to the container object Foo in every instance of Bar. So, I'm using a forward declaration in Bar.h that looks like this, at the top of that file:

class Foo;

Very simple stuff. This works fine.

Now, I would actually like to do more than just have a reference to Foo inside of Bar. I would like to have access to Foo's innards as well. However, when I try to access any of Foo's innards from Bar, I get a compilation error message that looks like this:

Bar.cc: In member function 'uint16_t Bar::bar() const':
Bar.cc:94: error: invalid use of incomplete type 'const struct Foo'
Bar.h:35: error: forward declaration of 'const struct Foo'
*** Error code 1

To reiterate, I have Foo using Bar's internals and Bar using Foo's internals, both are defined in separate .h and .cc files.

Is this a situation to absolutely avoid, or is there a solution around this?

If needed I will provide code samples, but I don't think it's necessary.
So you have this, then:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//foo.h
#include "bar.h"

class Foo{
    Bar a;
};

//bar.h
class Foo;

class Bar{
    Foo &a
};

//foo.cc
#include "foo.h"

//bar.cc 

Right? And you want to use member of Foo from Bar. Just include foo.h in bar.cc (not in bar.h, or you'll have mutually inclusive headers).
Wow thank you so much! That works perfect! Should have thought of that myself. For some reason I thought that including it like that was not ``correct''.
Topic archived. No new replies allowed.