Constructor Errors Between Classes
Aug 21, 2023 at 10:40pm UTC
I'm building a LinkedList data structure with a nested Node class. The Node class within the LinkedList class looks like this:
1 2 3 4 5 6 7 8 9 10 11 12
class Node {
public :
Node(){
this ->next = nullptr ;
this ->prev = nullptr ;
}
T data;
Node* next;
Node* prev;
};
My main function looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include "linked_list.h"
class Animal{
public :
Animal(std::string str){
this ->name = str;
}
std::string getName(){
return this ->name;
}
private :
std::string name;
};
int main() {
LinkedList<Animal>* AList = new LinkedList<Animal>(0);
Animal* a = new Animal("Fluffy" );
AList->add_last(*a);
return 0;
}
When I run this code, I get the following error:
error: no matching function for call to 'Animal::Animal()'
16 | Node(){
| ^
C:/LinkedListcpp/main.cpp:6:5: note: candidate: 'Animal::Animal(std::string)'
6 | Animal(std::string str){
| ^~~~~~
C:/LinkedListcpp/main.cpp:6:5: note: candidate expects 1 argument, 0 provided
Any ideas what is causing this problem?
Last edited on Aug 21, 2023 at 10:42pm UTC
Aug 21, 2023 at 10:47pm UTC
The data member of the Node class is "default-initialized" but Animal does not have a default constructor.
Aug 22, 2023 at 8:57am UTC
Perhaps what you meant to do was
1 2
LinkedList<Animal *> AList;
AList.add_last(new Animal("Fluffy" ));
This code looks suspiciously Java-ey. If I'm right and you already know Java, you should be careful about trying to import Java patterns into C++. The languages are not as similar as they appear superficially.
Topic archived. No new replies allowed.