c++ – Im getting an error invalid use of incomplete type class map

c++ – Im getting an error invalid use of incomplete type class map

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so its ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you cant use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what its working with.

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will not pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

c++ – Im getting an error invalid use of incomplete type class map

Leave a Reply

Your email address will not be published.