PDA

View Full Version : Cast problem



yellowmat
7th February 2006, 16:19
Hi,

I have a base class called CItem and 3 derived class called respectively CItemSound, CItemImage and CItemColor.

My application uses a QValueList<CItem>objList member to manipulate all my objets (of type CItemSound, CItemImage and CItemColor) regardless to their type.

I declare the objList member as follow :

QValueList<CItem>objList;
and I fill it as follow :

CItemSound s1;
s1.setItemName("Sound 1 of list 1");
CItemImage i1;
i1.setItemName("Image 1 of list 1");
CItemColor c1;
c1.setItemName("Color 1 of list 1");
list1.append(s1);
list1.append(i1);
list1.append(c1);


Let me explain my problem now :
in a function I need to do something like this :

CItemSound s = objList[0];
... it fails ... how is it possible to do such a cast ?

Thanks in advance

Codepoet
7th February 2006, 16:30
You are trying to assign a CItemSound variable the contents of a CItem variable. That is never valid because the compiler can't set all fields of the derived class.

You have another problem: QValueList stores by value: That means all your classes get "sliced" to fit into a CItem base class. You simply lose all other information they contain. Store instead pointers to instances of your classes - these you can cast any way you want. But ensure that you don't cast a CItemImage to a CItemSound.

yellowmat
7th February 2006, 16:32
hmm, ok, I try right now

yellowmat
7th February 2006, 16:57
ok, that's fine.

Thanks