Let's say I have this simple container class
class Array{
private:
int m_l{};
int *m_d{};
public:
Array() = default;
Array(int len)
: m_l{len}
{
assert(len >= 0);
if (len > 0)
{
m_d = new int[len]{};
}
}
~Array(){
delete[] m_d;
}
// -------------------------------------------
int& operator[](int i){
assert(i >= 0 && i <= m_l && "Index in operator [] out of range");
return m_d[i];
}
//--------------------------------------------
};
Specifically
int& operator[](int i)
{
assert(i >= 0 && i <= m_l && "Index in operator [] out of range");
return m_d[i];
}
I have overloaded the []
operator to get the subscript, I am just learning about operator overloading and container classes.
Array arr{5};
arr[0] = 32;
arr[1] = 34;
std::cout << arr[0];
32
The code compiles and executes as expected, but if I remove the &
from the function, making it
int operator[](int i)
{
assert(i >= 0 && i <= m_l && "Index in operator [] out of range");
return m_d[i];
}
The compiler throws an error
lvalue required as left of operand assignment
Why does this error occur, what is the significance of &
in the function?