Reputation: 12334
Hey, In C++, I have a vector of type:
vector<BaseClass*> myVector;
In which, I insert (push_back) pointers of derived classes into it.
Now, I want to pop back its elements so I do this:
vector<ADlgcDev*>::iterator iter;
for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)
{
// but before I pop it, I need to shutdown it down
// so I cast this
// but this way, I'm unable to call the function
(DerivedClass*(*iter))->Shutdown();
myVector.pop_back();
}
but as mention in the comments before I pop it, I need to call its Shutdown() method and the cast is not working properly too. Any resolutions? or is impossible?
Upvotes: 5
Views: 13240
Reputation: 6080
Could you make Shutdown a virtual function in BaseClass? Then you wouldn't need a cast.
Also you'll probably have trouble removing items from a vector while iterating. I'd do it like this:
vector<BaseClass*>::iterator iter;
for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)
{
(*iter)->Shutdown();
}
myVector.clear();
Edit: and another thing, ++iter is generally preferred over iter++.
Upvotes: 2
Reputation: 224049
while (!myVector.empty())
{
((DerivedClass*)(myVector.back()))->Shutdown();
myVector.pop_back();
}
Notes:
dynamic_cast
instead of the hard cast. (If it's sure that there are only DerivedClass
objects in the vector, why isn't it std::vector<DerivedClass>
?) Shutdown()
should be declared in the base class. Shutdown()
(and delete
, probably). Edit: Using std::vector<T>::clear()
, as shown by markh44 is probably better than the pop_back()
.
Upvotes: 12
Reputation: 3500
If Shutdown() is a virtual method of the Base class i.e. BaseClass::ShutDown() you should directly call iter->ShutDown();
Otherwise if the method isn't virtual you should use dynamic_cast
.
vector<ADlgcDev*>::iterator iter;
for (iter = myVector.rbegin(); iter != myVector.end(); iter++)
{
DerivedClassA* a = dynamic_cast<DerivedClassA*>( *iter ) ;
if ( a ) a->ShutDownA();
else
{
DerivedClassB* b = dynamic_cast<DerivedClassB*>(*iter);
if ( b ) b->ShutDownB();
// ... repeat for every class in hierarchy that might be in the vector.
}
myVector.pop_back();
}
Anyway you're probably leaking memory, unless ShutDown() deletes the object from itself (which is generally a bad idea ) or you're keeping duplicated pointers and deleting them elsewhere, which is another risky idea.
Upvotes: -1
Reputation: 14392
The constructor casting doesn't work for pointers. Use static_cast if you're sure or dynamic_cast and check.
Upvotes: 1