Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector Iterators Casting

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?

like image 658
akif Avatar asked Sep 03 '09 09:09

akif


2 Answers

while (!myVector.empty())
{
  ((DerivedClass*)(myVector.back()))->Shutdown();
  myVector.pop_back();
}

Notes:

  • You should probably use 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>?)
  • You should probably not have to cast at all, since Shutdown() should be declared in the base class.
  • You should probably delete the objects, too, before you pop them off the vector. (But that might not be so.)
  • You should probably use a smart pointer which calls Shutdown() (and delete, probably).

Edit: Using std::vector<T>::clear(), as shown by markh44 is probably better than the pop_back().

like image 116
sbi Avatar answered Oct 18 '22 08:10

sbi


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++.

like image 45
markh44 Avatar answered Oct 18 '22 07:10

markh44