Wednesday 15 January 2014

c++ - Is it possible to return an 'accurate' object from a polymorphic container of pointers? -



c++ - Is it possible to return an 'accurate' object from a polymorphic container of pointers? -

i found out whenever want polymorphism, need pointers or references, because storing derived instance in base variable 'slices' off isn't defined in 'base'.

(i suppose that's because derived , base instances don't occupy same space in memory. correct?)

so when want container holds kinds of objects, derived subclasses of base, need container of pointers , not container of actual objects.

and if want function gets object container , returns 'as is' (not sliced), can this:

base* get_pointer(int index) { homecoming container[index]; }

but want following:

base get_object(int index) { homecoming *container[index]; }

i.e.: homecoming real object, not pointer. possible? or should manage pointers when want kind of polymorphism?

i know whenever want polymorphism, need pointers or references [...] correct?

that absolutely correct. however, not limited "plain" pointers built language. smart pointers, such std::unique_ptr<t> , std::shared_ptr<t> nowadays improve alternative lets preserve polymorphic behavior.

[i want to] homecoming real object, not pointer. possible?

you can that, slicing back. base returned value, result stripped of derived functionality. happens when pass or homecoming value (passing , returning 2 sides of same thing, basic mechanism in play same in both cases).

if homecoming base& reference, however, same syntax in caller, , objects not sliced:

base& get_object(int index) { homecoming *container[index]; }

the grab item in container must remain in place while code holding reference it.

c++ pointers polymorphism

No comments:

Post a Comment