What I am trying to do is the following:

ReceiptBag zero("zero");
ReceiptBag one("one");
ReceiptBag bags[2];
bags = &zero;
(bags+1) = &one;

Of course that is not valid code.

My goal is to be able to reference the same zero or one object by using its variable name or by dereferencing the bags array. I don't think bags needs to be an array--I have gotten the impression there is someway to use a plain pointer to replicate the affect of an array, but I can't figure out the syntax for that either.

Initially I tried to do the following

ReceiptBag zero("zero");
ReceiptBag one("one");
ReceiptBag bags[] = {zero, one};

But this appears to use the auto copy constructor on the ReceiptBag objects. Therefore bags* references a different ReceiptBag object than zero.

I have tried some other things as well, but they all appear to be invalid syntax.

I'm pretty sure this is an easy thing to do, but google results in close but unrelated problems.

why not just make the array of pointers (note that arrays of references are illegal).

ReceiptBag zero("zero");
ReceiptBag one("one");
ReceiptBag * bags[] = {&zero, &one};

why not just make the array of pointers (note that arrays of references are illegal).

ReceiptBag zero("zero");
ReceiptBag one("one");
ReceiptBag * bags[] = {&zero, &one};

This is something I considered, and it seems fine. However, that means I will end up doing something like:

(*bags[0]).someReceiptBagFunction();

I would prefer to be able to just:

bags[0].someReceiptBagFunction();

But judging by the fact that you were not aware of way to accomplish the goal directly, I'm guessing there is no such way, and instead your suggestion is as close as it gets.

Hmm, it seems strange that such a thing is not possible. Perhaps, arrays must be composed of contiguous addresses, therefore being able to modify or set the addresses of an array would break it.

Anyone have any insight on the issue?

Then how about

ReceiptBag bags[] = {"zero", "one"};
ReceiptBag &zero = bags[0];
ReceiptBag &one = bags[1];

:icon_mrgreen:

>>(*bags[0]).someReceiptBagFunction();

Or, more simply bags[0]->someReceiptBagFunction();

Caligulaminus, when I first saw your post I didn't think it would compile--I had never used a reference type like that. But what you suggested totally works. Also, I am glad you brought that auto cast to my attention, I had heard of it, but I wouldn't have thought to use it there.

AncientDragon, the use of the structure dereference operator is not bad at all, if I had known about it I would have gone with an array of pointers, since using a -> is not as ugly as an asterisk wrapped in parenthesis.

Anyway, the combined suggestions from you guys solved my immediate problem and will help me in the future. So, thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.