Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() {}
};
like image 693
marathon Avatar asked Nov 10 '22 23:11

marathon


1 Answers

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.

like image 53
Neil Kirk Avatar answered Nov 14 '22 22:11

Neil Kirk