A list of reference?

F

foggy

Derived1 and Derived2 are derived from BaseClass:

list<BaseClass&> lst;
Derived1 d1;
Derived2 d2;
lst.push_back(d1);
lst.push_back(d2);

Can a list be created like above so that d1, d2... objects can be navigated
to?

I read somewhere "A list container should not contain a list of references
since they are not assignable." What does this mean? Thanks!
 
J

John Harrison

foggy said:
Derived1 and Derived2 are derived from BaseClass:

list<BaseClass&> lst;
Derived1 d1;
Derived2 d2;
lst.push_back(d1);
lst.push_back(d2);

Can a list be created like above so that d1, d2... objects can be navigated
to?

No, use pointers instead.
I read somewhere "A list container should not contain a list of references
since they are not assignable." What does this mean? Thanks!

Err, exactly what it says (except I would say 'cannot' not 'should not').
Lists make some assumptions on the objects they contain, one of which is
that the objects themselves can be assigned. References cannot be assigned

int a = 1;
int b = 2;
int& r = a;
r = b;

r = b does not assign to the reference, it assigns the value of b to a, r
still refers to a.

john
 
M

Michiel Salters

foggy said:
Derived1 and Derived2 are derived from BaseClass:

list<BaseClass&> lst;
Derived1 d1;
Derived2 d2;
lst.push_back(d1);
lst.push_back(d2);

Can a list be created like above so that d1, d2... objects can be navigated
to?

Use boost::reference_wrapper<BaseClass> instead of BaseClass&.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,166
Messages
2,570,901
Members
47,442
Latest member
KevinLocki

Latest Threads

Top