How to fix an "field has incomplete type" error when using a forward declaration

marathon picture marathon · Oct 29, 2014 · Viewed 15.4k times · Source

This code throws the compiler error error: field ‘fTarget’ has incomplete type as noted in the comments. Why is this happening? I'm only assigning that field and not doing any operations that would need to know what is inside... or am I? Maybe it can't figure out the copy constructor?

class FSRVertex;  //fwd

class FSREdge
 {
 public:
    char fC;
    FSRVertex fTarget;   //compiler error
    FSREdge(char c, FSRVertex target) : fC(c), fTarget(target) {}  //compiler error
};


class FSRVertex {
public:
    boost::unordered_map<char, FSREdge> fOutEdges;
    FSRVertex() : fOutEdges() {}
};

Answer

Neil Kirk picture Neil Kirk · Oct 29, 2014

To have an FSRVertex object as a member of your class, the compiler needs to know its size, and so needs to see its full definition.

Either provide the full definition for your class, or you can store a pointer (preferably smart pointer) to a dynamically allocated copy of the object performed in the constructor. You will need to move the constructor body outside the class to a place where the full definition is provided. This approach is less efficient at run-time.