I have an
std::list<TYPE>
which may contain child classes of TYPE. I need to iterate over the list and call the child’s overridden version of a function defined in TYPE but I won’t know which subclass of TYPE I have and the reference is of type TYPE.
If I call using the TYPE reference it will call the TYPE’s virtual method and not my subclass method. Is there a way to say “call the furthest subclass’ overridden version of this method”?
You can’t store references in a
std::listand your list doesn’t contain instances of a subclass ofTYPE.If you assign an instance of a subclass of
TYPEto aTYPE, it gets “sliced”, which means that all subclass information is lost. This is why theTYPEmethod is called – the object is aTYPE, not a subclass ofTYPE.If you want polymorphism you must store pointers –
TYPE*or a smart pointer – in the list.