Search code examples
c++structinitializationinitializer-list

no matching constructor for initialization of 'listNode struct


The following method insert makes use of the constructor for the struct listNode.

void list::insert(size_t i){
    if (head == nullptr){
        head = new listNode(nullptr,i);
        tail = head;
        ++len;
    }
    listNode* new_node = new listNode(nullptr,i);
    tail->next = new_node;
    tail = new_node;
}

definition of listNode

struct listNode{
        ////@: index into the input buffer
        listNode* next;
        size_t index;
};

in addition to the error given in the title of this post, I also get the note

 note: candidate constructor (the implicit copy constructor) not
      viable: requires 1 argument, but 2 were provided
struct listNode{

this doesn't make sense to me. As clearly i provided two arguments in my initialization and it should use lexicogrphical binding of paramaters to actual paramaters.


Solution

  • head = new listNode(nullptr,i);
    

    is wrong since listNode does not have any user defined constructors. Hence, you cannot use the syntax listNode(nullptr, i) to construct one.

    Use

    head = new listNode{nullptr, i}; // This is member-member wise initialization
    

    Similarly, instead of

    listNode* new_node = new listNode(nullptr, i);
    

    use

    listNode* new_node = new listNode{nullptr, i};