0

I'm following a linked list implementation from a textbook and I'm getting the error "call to constructor of 'Node' is ambiguous in this private function within my LinkedList.cpp:

void P1LinkedList::init(){
    theSize = 0;
    head = new Node;    //causes error
    tail = new Node;    //causes error
    head->next = tail; 
    tail->prev = head; 
} 

This is my Node.h:

#ifndef Node_h
#define Node_h
struct Node{

        int data; 
        Node* next; 
        Node* prev; 

        Node(const int & d = 0, Node *p = nullptr, Node *n = nullptr); 
        Node(int && d = 0, Node *p = nullptr, Node *n = nullptr); 
};
#endif

And my Node.cpp:

#include "Node.h"
#include<iostream>

Node::Node(const int & d, Node *p, Node *n)
    :data{d}, prev{p}, next{n}{}

Node::Node(int && d, Node *p, Node *n)
    :data{std::move(d)}, prev{p}, next{n}{}

I'm guessing it has to do with how I've written the Node constructors, but I've written it according to my textbook's outline so I'm not sure what I've done wrong.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
hmp54
  • 43
  • 1
  • 6
  • 2
    Which constructor do you expect to be called, and why ? – Sid S Jan 20 '20 at 21:42
  • 3
    Your textbook told you to write a constructor taking `int &&`? How far into the textbook is this exercise? Have rvalue references even been introduced properly already? The second constructor would make sense if this was a generic list implementation for arbitrary element type, but it doesn't make sense for `int`. – walnut Jan 20 '20 at 21:47
  • @walnut the exercise is at the beginning of my data structures textbook. I've never worked with C++ before taking data structures this semester, so I'm finding myself learning the language as I go through the book. Thanks for letting me know about the generic list implementation vs. int implementation; the book originally implements it as a generic list, but I've been using it as a guide for an int implementation. – hmp54 Jan 20 '20 at 23:24
  • @hmp54 Then it seems that the book is assuming prior knowledge of C++. I suggest you work through a [good C++ introductory book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), so catch up to that. – walnut Jan 20 '20 at 23:35

1 Answers1

3

You've written two constructors which both could be called with an empty parameter list. As a consequence, the compiler cannot know which constructor you intended to call and neither can be called.

Solution: Decide which constructor you intend to call and make sure that the other one is not callable with those parameters (in this case, with no parameters).

In this very particular case, simply remove the second constructor. It doesn't do anything that the first doesn't do.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Another general solution would be to add a constructor with no parameters; and remove the default argument from the first parameter of the others – M.M Jan 20 '20 at 21:55