I’m doing a program that manages a collection of items. That can be a Book, a Magazine, a CD or a DVD. Each of those is a class thats inherits the class Item. To store those items I’m using the list template, like this:
list<Item> items;
and this list is inside an object lib of the class Library.
To run through this list I’m doing this:
for(list<Item>::iterator i = lib.itens.begin(); i != lib.itens.end(); ++i)
Until this point everything’s fine. The problem starts when I try to call a method of the derived class inside this loop. example:
for(list<Item>::iterator i = lib.itens.begin(); i != lib.itens.end(); ++i)
(*i).lib.itens.show();
How can I call those methods?
There are at least two problems here. Firstly, if you do this:
then this list really will only contain
Itemobjects; if you try to put in a derived object, the derived part will simply be sliced off.One solution is to use a list of pointers instead (although you should probably use smart pointers to avoid memory-management issues).
But even then, the second issue is that you shouldn’t (in general) be trying to call derived-class-specific methods via pointers to the base class. The whole point of polymorphism is that you should only be dealing in terms of base-class pointers if you’re happy to work with functionality that’s common to the whole hierarchy (see Liskov substitution principle).