views:

247

answers:

2

I have two classes that depend on each other:

class Foo; //forward declaration

template <typename T>
class Bar {
  public:
    Foo* foo_ptr;
    void DoSomething() {
      foo_ptr->DoSomething();
    }
};

class Foo {
  public:
    Bar<Foo>* bar_ptr;
    void DoSomething() {
      bar_ptr->DoSomething();
    }
};

When I compile it in g++, it was giving error of "Invalid use of incomplete type", but it was compiled nicely in MSVC 10. Is it possible to solve this problem while keeping the declaration and definition in one header file? (no cpp files) If this is not allowed in the standard, so is this one of the MSVC "bug" or "feature"?

A: 

See this page: http://stackoverflow.com/questions/2143714/what-is-the-best-way-to-deal-with-co-dependent-classes-in-c

It should clear up the problem and provides a couple nice solutions.

George Edison
Just linking to other answers on SO should be done via comments, not as an answer.
Georg Fritzsche
Good point. I kind of forgot in my haste.
George Edison
+3  A: 

Yes, just move the method definitions out of the class definition:

class Foo; //forward declaration

template <typename T>
class Bar {
  public:
    Foo* foo_ptr;
    void DoSomething();
};

class Foo {
  public:
    Bar<Foo>* bar_ptr;
    void DoSomething() {
      bar_ptr->DoSomething();
    }
};

// Don't forget to make the function inline or you'll end up
// with multiple definitions
template <typename T>
inline void Bar<T>::DoSomething() {
  foo_ptr->DoSomething();
}
R Samuel Klatchko
So there is no way of making it works without separating the class implementation from the definition?
leiiv
@leiiv - I don't know of any portable way. But just to be clear, the implementation can still go in the header file; no new source file is required.
R Samuel Klatchko