How to fix "field is incomplete type" error when using forward declaration
This code generates a compiler error error: field โfTargetโ has incomplete type
as pointed out in the comments. Why is this happening? I only assign this field and do not do any operations that would have to know what is inside ... or me? Maybe it can't define a 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() {}
};
source to share
To have an FSRVertex object as a member of your class, the compiler must know its size and therefore must see its full definition.
Either provide a complete definition for your class, or you can store a pointer (preferably a smart pointer) to a dynamically allocated copy of the object executed in the constructor. You will need to move the body of the constructor outside of the class to the location where the full definition is provided. This approach is less efficient at runtime.
source to share
You can always make FSRVertex
a template parameter FSREdge
. Then the compiler must wait with the computation of the size FSREdge
until specialization and knowledge of the size are FSRVertex
no longer a problem. It's a bit dumb, but it does what you want and there is no runtime overhead:
class FSRVertex; // fwd
template <class FSRVertex_Forward = FSRVertex> // make fwd the default type
class FSREdge_ {
public:
char fC;
FSRVertex_Forward fTarget;
FSREdge_(char c, FSRVertex_Forward target)
:fC(c), fTarget(target)
{}
FSREdge_(const FSREdge_ &other) // std::map requires copy ctor
:fC(other.fC), fTarget(other.fTarget)
{}
FSREdge_() // std::map requires default ctor
{}
};
typedef FSREdge_<> FSREdge; // so that you don't have to carry the brackets everywhere
class FSRVertex {
public:
std::map<char, FSREdge> fOutEdges;
FSRVertex()
:fOutEdges()
{}
};
You can see this work at ideone .
source to share