0

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].

3
  • 6
    If you are asking about return elem[i];, that doesn't return a pointer. The [] operator derferences the pointer. Commented Jul 7, 2019 at 13:05
  • 5
    No, elem[i] is the same as *(elem+i). The asterisk is very important. Commented Jul 7, 2019 at 13:41
  • Damn, didn't know that. Thanks a lot for explanation! Commented Jul 7, 2019 at 13:51

1 Answer 1

1

Per [expr.sub]/1:

A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall be a glvalue of type “array of T” or a prvalue of type “pointer to T” and the other shall be a prvalue of unscoped enumeration or integral type. The result is of type “T”. The type “T” shall be a completely-defined object type. The expression E1[E2] is identical (by definition) to *((E1)+(E2)), except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise. The expression E1 is sequenced before the expression E2.

Here, elem is of type double*, and i is of type int. elem[i] is by definition equivalent to *(elem + i), which is an lvalue of type double. *elem[i] attempts to dereference a double, which is ill-formed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.