Subscript Operator Overloading Error
-
08-12-2019 - |
Question
This is a function within my doubly linked list class, but every time I compile, I get this message: "Invalid initialization of non-const reference of type 'int&' from a temporary of type 'int'. I just can't get how else to do it.
int& LinkedList::operator[](int index)
{
Node* current = head_;
for(int i = 0; i < index; i++){
current = current->getNextNode();
}
return(current->getValue()); // getValue() returns an int
}
Thanks in advance!
Solution
Simple answer: getValue
has to return an int&
as well.
OTHER TIPS
If you want to be able to use this to modify the value stored in the list, then it will have to return a reference to that value. That means that you'll need to either make Node::getValue()
return a reference, or add another way to get a reference to the value stored in the node.
If you don't want to use this to modify the list contents, then you could change the return type to int
.
The problem is that you cannot bind a non-const reference to an rvalue (in this case the temporary returned by the getValue()
function). If you want to provide a reference to the value stored in the list so that it can be modified by the caller you will need to modify getValue()
to return a reference.
As of the general idea, you might want to consider offering a random access operation to the list. It might give the wrong idea that it is a cheap. Users might, for example try to iterate over the list like:
for (int i = 0; i < list.size(); ++i)
std::cout << list[i] << std::endl;
But that iteration is actually O(N^2) rather than O(N)
(You should, you know, just use std::list
... which doesn't offer this operation for a reason...)
The reason you are returning int&
is so that someone who writes mylist[i] = 42
will actually modify the contents of the list.
However, you are getting at the value by using the getValue
helper which, based on the error message, returns a copy. The compiler has, by analyzing the data types, found your logical error. If you want to be able to modify the actual list data, then you have to return a reference to the actual list data, not a copy.
Thus, getValue
needs to return int&
as well, as Philipp suggests.