Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot cast list iterator to an object

Tags:

c++

I get the error:

error C2682: cannot use 'dynamic_cast' to convert from 'std::_List_iterator<_Mylist>' to 'UserBean *'

When executing:

list<UserBean> * userBeans = getUserBeans();

for(list<UserBean>::iterator i = userBeans->begin(); i != userBeans->end(); i++)
   UserBean * newUser = dynamic_cast<UserBean*>(i);

Am I doing something wrong, or can you not convert iterator items to objects?

like image 487
samwell Avatar asked Nov 30 '22 21:11

samwell


1 Answers

Sometimes iterators are implemented as raw pointers to container items, but more times than not, they are not pointers at all, so don't treat them that way. The correct way to access the item that an iterator refers to is to dereference the iterator, eg:

UserBean &newUser = *i;

Or:

UserBean *newUser = &(*i);

Iterators usually override the -> operator so you can access members of the referenced item, in cases where the iterator refers to an actual object instance (which yours does) and not a pointer to an object instance, eg:

i->SomeMemberHere
like image 178
Remy Lebeau Avatar answered Dec 03 '22 12:12

Remy Lebeau