I'm new to c++ learning to implement linked lists, i don't understand why i when i don't call by reference in the arguments of the function insertAtfront the output becomes wrong? and why does the argument have to be const reference?
#include <iostream>
template <typename T>
class List {
public:
const T & operator[](unsigned int data);
void insertAtFront(const T & data);//&
private:
class ListNode {
public:
const T & data;
ListNode * next;
ListNode(const T & data_): data(data_), next(nullptr){} //&
};
ListNode * head_=nullptr;
};
template <typename T>
const T & List<T>::operator[](unsigned int index){
ListNode * through=head_;
while(index>0 && through->next!=nullptr){
through = through->next;
index--;
}
return through->data;
}
template <typename T>
void List<T>::insertAtFront(const T & data){ //&
ListNode * Ptr=new ListNode(data);
Ptr->next=head_;
head_=Ptr;
}
int main(){
List<int> L;
L.insertAtFront(2);
L.insertAtFront(55);
std::cout<<L[0]<<std::endl;
std::cout<<L[1]<<std::endl;
}