Reference to one of many objects

I have several different objects, each with a common base class. Id like to create a base-class reference to the i-th object. Is there a better way than:

1
2
3
4
5
Base& base = (i == 0) ? Obj0 :
             (i == 1) ? Obj1 :
             (i == 2) ? Obj2 :
...
             (i == 7) ? Obj7;

Last edited on
try if statements or for loop or both
Neither seem to work:

1
2
Base& base;
if (i == 1) base = Obj1;


 
if (i == 1) Base& base = Obj1;


The first statement is invalid. Moving it into the if means the reference is out of scope. Same with for loops.
Last edited on
Don't use numbered variables. Use an array instead.

1
2
3
Object Obj[8];
// ...
Base& base = Obj[i];

You can't use ifs since references must be initialized when defined and afterwards can't be changed.
Last edited on
What dutch said.

If you absolutely cannot use an array (and if you cannot, I suggest you go back and look at your design again), then use a pointer instead of the reference.
I can't use an array as each object is a different class, though all inherited from the same base. But maybe I can use a tuple? I'll give this a try. The other option I found was, as you suggested, using base pointers with if's, then creating the reference from *pointer. I was just looking for something more streamlined/clever. Thanks all for your help!
Topic archived. No new replies allowed.