Object of inheriting class in base class?

How would I declare an object of a class in the class it inherits from? Without the "#include "Bar.h"", my compiler says Bar doesn't name a type. With it, my compiler says it expected a class-name before '{'. I can't seem to figure out why I can't do this; I couldn't find an answer when I looked it up with Google.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Foo.h:

#include "Bar.h"

class Foo
{
    public:
        static Bar bar;
};

// Bar.h:

#include "Foo.h"

class Bar: public Foo
{
    public:
        int barInt;
};


Thanks,
Pyrius
If the object is not static, it is impossible since the child and parent classes will try to instantiate each other, making each of them impossible to instantiate.

However, if the object is static, you can get around this by having a global variable in Foo's source file. If access to the object is needed outside of Foo, you can have a reference to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
// foo.h
#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED

class Bar;  // forward declare Bar

class Foo
{
public:
  static Bar& bar;  // a reference to the global Bar object
};

#endif 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// foo.cpp

#include "foo.h"
#include "bar.h"

namespace
{
  Bar theGlobalBar;  // instantiate the global bar object globally
         // I put in an anon namespace to prevent pollution in other source files
         //  ... while recommended, it is not necessary
}

// initialize Foo::bar to refer to this global Bar object
Bar& Foo::bar( theGlobalBar );
Last edited on
Hmm.. actually... I wonder if forward declaring would work. I just assumed it wouldn't, but it might.

I'll have to try that out when I get home.
Thanks, Disch. I got rid of the error.
Topic archived. No new replies allowed.