In C++, it's illegal to have arrays of references. In a question about it, the second voted answer claims that "References are not objects. They don't have storage of their own, they just reference existing objects. For this reason it doesn't make sense to have arrays of references.".
Firstly, I'd like to understand why it doesn't make sense to have an array of references.
My assumption for why that might be is, that anywhere a reference is used, it is automatically 'translated' to the object it references. So saying arrayOfReferences[5] = refToObj
is equivalent to saying arrayOfReferences[5] = obj
. resToObj
is always implicitly translated to obj
. So making an array of references to object, is equivalent to simply making an array of objects. Is this assumption correct?
If it is, than I have another question:
In C++, if we want polymorphism we can use either pointers or references. Storing an object of a Thing
subclass in a Thing*
allows us polymorphism, and so does storing it in a Thing&
. However storing it in a Thing
'slices' the extra non-Thing
stuff, and leaves us with a plain Thing
.
So if we agree that an array of references is equivalent to an array of objects - great, I can just use a normal array of objects. But than - I lose polymorphism. I can store all kinds of Thing
objects in a Thing[]
, but they will all be sliced to a simple Thing
.
So, the second question is: is there a way to store objects in an array and retain their concrete type and polymorphism, without using pointers (i.e. Thing*[]
)?