PDA

View Full Version : casting qvector element



rivci
4th April 2011, 13:52
Hello,

I am java user before and I want to use polymorphism in C++, but I got some errors.


Consider I make a class A
Then I make class B which subclass A
I make a --> QVector<A> vec;
I instantiate an object from class B --> B objB;
I insert it into vector --> vec.append( objB );
I try to extract an element from my vector, but this gives error --> B objB = vec.at(0); (ERROR)


Anyone help me pliz, urgent :)

just to add more info, I used static_cast and dynamic_cast but didn't seem to work

Zlatomir
4th April 2011, 13:58
QVector<A> vec; will truncate all the B objects (you will have only A in the vector)

You need to use QVector of pointers to A and then initialize the pointers with addresses of A or B objects and then the polymorphism will work, but be careful to initialize the pointers.

LE: if you use heap memory (if you use new to initialize pointers from QVector) you need to delete the memory yourself.
//i assume your A and B are not in some QObject hierarchy (and use parent-child) - if they are or if you use some smart-pointers check their documentation to check what gets automatically deleted and what you need to delete.