UPDATE: The issue was stemming from the fact that the Passenger class does not have a default constructor. I don't understand why that breaks the list implementation though. If someone could leave a comment explaining this to me, I'd appreciate it a lot!
OG Post:
Hello fellow stackoverflowers. I'm working on a simple university assignment but have run into a problem I can't seem to wrap my head around to solve. I'm new to C and I'm learning now that implementing generics is not as straightforward in C as it is in Java. Inside my LinkedList class there is a struct Node:
struct Node {
T data;
Node *next;
}; // Node
Simple enough. And when I create a list of integers in my main.cpp, the implementation functions as it should.
int main() {
LinkedList<int> integers;
integers.append(1);
integers.append(2);
integers.append(3);
// append, prepend, get, insert, and remove
// functions all work as they should.
} // main
I also have a Passenger class. The problem occurs when I attempt to create a list of Passenger instances.
int main() {
LinkedList<Passenger> passengers;
Passenger passenger1("LastName1", "FirstName1", 0);
Passenger passenger2("LastName2", "FirstName2", 1);
passengers.append(passenger1);
passengers.append(passenger2);
} // main
The error messages read exactly as follows:
./LinkedList.hpp:21:10: error: implicit default constructor
for 'LinkedList<Passenger>::Node' must explicitly initialize
the member 'data' which does not have a default constructor
./LinkedList.cpp:26:23: note: in implicit default constructor
for 'LinkedList<Passenger>::Node' first required here:
Node *newNode = new Node;
The append function in the LinkedList class is the following:
template<class T>
void LinkedList<T>::append(T data) {
Node *newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
newNode->next = head;
this->head = newNode;
} else {
Node *ptr = head;
while (ptr->next != NULL) {
ptr = ptr->next;
} // while
ptr->next = newNode;
} // if
length ;
} // append
Thank you so much to anyone who helps me out here!
CodePudding user response:
It appears that you call:
Node *newNode = new Node;
Which is equivalent to
Passenger *newNode = new Passenger;
Which appears to be invalid because Passenger
does not have a no argument constructor. I suspect you could fix this by doing:
Node *newNode = new Node(data, nullptr);