I’m writing a class that wraps a dynamically allocated array and I’m trying to write the operator[] function. Currently I have:
bool& solution::operator[](unsigned int pos)
{
if(pos < _size)
{
return this->_data[pos];
}
else
{
return false;
}
}
But I get the following error from g++:
error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘bool’
How should I be doing this? I need the [] operator to be able to modify elements.
Its because the boolean literal
falsewhich is a rvalue, cannot be bound to non-const referencebool&which is the return type ofoperator[].Simply change the return type from
bool&tobool, the error will disappear. But that isn’t going to solve your problem, as you said,you want to return reference of the element, so that the element can be changed on the callsite, then you’ve to something like this:That is, you should notify the caller of an invalid index, so that it can know that something went wrong. C++ various exception classes are there exactly for that purpose, i.e to notify error.
Attempting to return any value (false or true) when the index is invalid, simply hides the problem. Ask yourself, if you return a dummy boolean value (which you store in the class), then would the caller know if the index was invalid? No.