user987316
user987316

Reputation: 942

Dynamic cast to vector iterator

I have below snippet-

std::vector<cMyClass> myCls = GetClassValues();
std::vector<cMyClass>::const_iterator imyCls;
for( imyCls = myCLs.begin(); imyCls != myCls.end(); ++imyCls)
{
  cMyClass *cls = dynamic_cast<cMyClass*>(*imyCls);//C2682


}

In for loop I want to have pointer variable of cMyClass, I can't use direct assignment or static cast. SO using dynamic_cast but that also doesn't seem to be working.

What option I have if I want to make it working.

Upvotes: 1

Views: 1864

Answers (2)

user2807083
user2807083

Reputation: 2972

At first, you try to get pointer from reference, you must add & before iterator dereferencing like this: &*myCls. Also, since you are using const_iterator, you can get const pointer only. Either change imyCls to non-const iterator, or change cast to const pointer version.

cMyClass const *cls = dynamic_cast<cMyClass const*>(&*imyCls);

Upvotes: 1

You can use

cMyClass *cls = &*imyCls;

*imyCls is a reference to the object in the vector; &*imyCls is the address of that.

Upvotes: 3

Related Questions