PDA

View Full Version : Containers with derived classes? (QMap or QList)



CSmith
7th May 2012, 16:08
Hi all,

This is my first post and early experience with Qt so appologies if this is answered elsewhere but i can not find it.

Here is an example of my problem.

I have base class 'Fruit' and several derived classes let's say 'Apple' and Bannana'

I want to store these in a container, for example a QMap.

So i have created a QMap of Fruits.

I know if i was writting in c# for example i could call the equivelant of typename or typeid on each item and the cast them back to 'Apple' or 'Bannana' when i read them out.

However it seems here i have lost all of the properties of Apple and Bannana and am left with just 'Fruit's.
If i call typename on each item it always returns 'Fruit'

Am i missing something or can i not create a list of derived classes by creating a list of the base class?

Hope this makes sense.

Thanks in advance. :)

amleto
7th May 2012, 16:47
if you store a list of fruits, then you should only need to treat them as fruits, otherwise your design is wrong (liskov substitution principle, I think).

You should only need to use virtual methods on Fruit to get specialised behaviour, and should not need to recover the exact type.

Tell me, how are the available properties of Apple different to that of Banana?


This is basic C++ and nothing to do with Qt.


If you make a QList<Fruit>, then you have only Fruit objects. If you make a QList<Fruit*>, then you may have Fruit, Apple and Banana...

CSmith
7th May 2012, 17:52
Thanks for the reply.

The problem i have is that i want to store a list of objects, this list is of different object types, some with common properties and some with different properties.
I then wanted to serialize this data.

Another application would then deserialize this data and obtain a list of objects. It could then iterate through them and act accordingly according to what type they were.

I have done this many times in other languages using the approach i mentioned (extending a base class and then creating a list of the base class)

I am fairly new to c++ but have much experience in other languages.

Thanks again.

amleto
7th May 2012, 18:42
then in c++ you must use a container of pointers or references then. You cannot use containers of base types if you want polymorphic behaviour - The container objects will be sliced if you attempt to store specialised objects.