Consider the following example class taken from Bjarne Stroustrup - A Tour of C++ (2nd edition):
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} { }
double& operator[](int i) { return elem[i]; }
int size() { return sz; }
private:
double* elem;
int sz = 0;
};
As far as I yet understand, in double& operator[] method body, elem[i] (which is the same as elem + i) has a type of pointer to double double*.
So, the question is: why is it correct returning pointer to double though method signature implies a reference to double (variable itself) to be returned?
Moreover, compiler throws an error if I tried returning dereferenced *elem[i] instead of elem[i].
return elem[i];, that doesn't return a pointer. The[]operator derferences the pointer.elem[i]is the same as*(elem+i). The asterisk is very important.