Search code examples
c++incomplete-type

c++ : error: member access into incomplete type , unused parameter [-Werror,-Wunused-parameter]


I have the following code:

class MyNode;

class MyCompare {
  public:
    bool operator()(MyNode *a, MyNode *b) {
        return a->q <= b->q ? true : false;
    }
};

class MyNode {

  public:

    double sum;    
    double q;

    StateNode *parent;
    std::priority_queue<MyNode, std::vector<MyNode>, MyCompare> children;
};

But got the following compiling errors:

error: member access into incomplete type 'MyNode'
        return a->q <= b->q ? true : false;
                ^
..MyNode.h:35:7: note: forward declaration of 'MyNode'
class MyNode;
      ^
..MyNode.h:39:46: error: unused parameter 'b' [-Werror,-Wunused-parameter]
    bool operator()(MyNode *a, MyNode *b) {

Any idea what I did wrong here? Thanks!


Solution

  • As the error message said, a->q and b->q, i.e. the usage of class member access operator requires the type MyNode to be complete type. Only forward declaration is not sufficient.

    The following types are incomplete types:

    • class type that has been declared (e.g. by forward declaration) but not defined;

    and

    Any of the following contexts requires class T to be complete:

    • class member access operator applied to an expression of type T;

    You can move the definition of operator() after the definition of MyNode, at that point MyNode is complete. e.g.

    class MyNode;
    
    class MyCompare {
      public:
        bool operator()(const MyNode *a, const MyNode *b) const;
    };
    
    class MyNode {
    
      public:
    
        double sum;    
        double q;
    
        StateNode *parent;
        std::priority_queue<MyNode, std::vector<MyNode>, MyCompare> children;
    };
    
    bool MyCompare::operator()(const MyNode *a, const MyNode *b) const {
        return a->q < b->q;
    }