Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid use of incomplete type on g++

Tags:

c++

class

g++

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"?

like image 866
leiiv Avatar asked Feb 17 '10 01:02

leiiv


People also ask

What is invalid use of incomplete type C++?

Solution: There are multiple possible issues, but in general this error means that GCC can't find the full declaration of the given class or struct.

What does incomplete type mean?

An incomplete type is a type that describes an identifier but lacks information needed to determine the size of the identifier. An incomplete type can be: A structure type whose members you have not yet specified. A union type whose members you have not yet specified.


1 Answers

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();
}
like image 77
R Samuel Klatchko Avatar answered Oct 16 '22 14:10

R Samuel Klatchko