AmatuerCoder101 AmatuerCoder101 - 3 months ago 32
C++ Question

Eclipse osx, no matching constructor

I am pretty sure my code is correct in terms of the arguments I am inputting to my function however on eclipse I am getting an error that there is no matching constructor. I was wondering if I need to change a setting in eclipse (it seems quite fiddly to get C++ to work so far on mac) or if there is an error in my code. So the code is a linked list of objects I have a node class which is then included in the linked list class.

the node constructor

Node::Node(Animal& a) : animal(a), next(0) {
}


then I call it in the linked list like this

void LinkedList::addAtIndex(const Animal& a, int index) {
Node *nodeToAdd = new Node(a);


the line above gives me an error no matching constructor for initialization of Node

Answer

In that context:

void LinkedList::addAtIndex(const Animal& a, int index) {
   Node *nodeToAdd = new Node(a);

a is expected to be constant. You're passing it to a constructor where you try to use the non-constant reference, thus violating the const contract/qualifier => can't do.

To fix that: Node::Node(const Animal& a) : animal(a), next(0)

if your member animal is not a non-const reference to Animal this will work, else you'll have to do the other way: remove the const qualifier from the addAtIndex method.