Hi, I was reading a code, the purpose of it is creating a class which could create a dynamic array. There are some questions in its declaration. Hopefully, someone could help me.
What I don't understand is that why the overloads of "=" and "[]" return references of T; however for the overload of "+", it returns an object of Array<T>.
Looking forward to some help, thank you very much.
= returns a reference to Array<T> to allow for "assignment chaining".
For example:
1 2 3 4 5 6 7 8
int a, b, c;
a = b = c = 5; // legal
// the above is the same as
c = 5;
b = c;
a = b;
For this to work in overloaded = operators, the operator returns a reference to itself so that it can act as the rhs for another = operator.
The [] operator returns a reference to a T so that the retrieved element can be read/written to:
1 2 3 4 5 6 7 8
Array<int> myarray;
// myarray[5] returns a reference to element 5 of the array
// references can be on the left or right side of an assignment:
int v = myarray[5]; // right side
myarray[5] = v; // left side. Both legal if [] returns a reference.
+ returns an object because it must create a new object. It cannot modify 'this'.
Example:
1 2 3 4 5 6 7
int a = 1;
int b = 2;
int c;
c = a + b; // this does not modify a or b.
// instead, a and b get added to a 'temporary' int, and that temporary int gets
// assigned to c