Results 1 to 2 of 2

Thread: casting qvector element

  1. #1
    Join Date
    Dec 2010
    Posts
    20
    Thanks
    9
    Thanked 3 Times in 1 Post
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: casting qvector element

    Hello,

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

    1. Consider I make a class A
    2. Then I make class B which subclass A
    3. I make a --> QVector<A> vec;
    4. I instantiate an object from class B --> B objB;
    5. I insert it into vector --> vec.append( objB );
    6. 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

  2. #2
    Join Date
    May 2010
    Location
    Romania
    Posts
    1,021
    Thanks
    62
    Thanked 260 Times in 246 Posts
    Qt products
    Qt5
    Platforms
    MacOS X Unix/X11 Windows Android

    Default Re: casting qvector element

    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.
    Last edited by Zlatomir; 4th April 2011 at 14:03.

  3. The following user says thank you to Zlatomir for this useful post:

    rivci (6th April 2011)

Similar Threads

  1. Can anybody explain me this 'kind of casting'¿?
    By tonnot in forum General Programming
    Replies: 6
    Last Post: 28th November 2010, 19:39
  2. Casting variables
    By axisdj in forum Newbie
    Replies: 1
    Last Post: 6th September 2010, 17:00
  3. Problem with type casting
    By qtDave in forum Newbie
    Replies: 7
    Last Post: 9th November 2009, 20:57
  4. Problem with type casting?
    By Jyoti.verma in forum Qt Programming
    Replies: 2
    Last Post: 25th August 2009, 05:24
  5. Casting QGraphicsItem
    By pherthyl in forum Qt Programming
    Replies: 1
    Last Post: 11th November 2007, 23:56

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.