impulsgraw
impulsgraw

Reputation: 897

Why returning pointer instead of variable itself is correct for functions with reference return type

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

Upvotes: 0

Views: 64

Answers (1)

L. F.
L. F.

Reputation: 20569

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.

Upvotes: 1

Related Questions