havingaball
havingaball

Reputation: 378

C++ Iterating over vector of class pointers and using base function

I am trying to loop over a vector of pointers to my class, let's call it MyClass, and call a method within MyClass for each element in the vector, let's call it MyMethod. That is:

std::vector<MyClass*> ClassOne;
for(auto it: ClassOne){
    ClassOne[it].MyMethod();
}

But evidently this does not work. Could someone please explain how to fix this but also what my code here is actually doing (as opposed to what I thought it should be doing).

Thanks!

Upvotes: 0

Views: 283

Answers (2)

asmmo
asmmo

Reputation: 7100

You are using range-based for loop, hence you should be using

for(auto it: ClassOne){
    it -> MyMethod();
}

it is not an index. It's a copy of the element (the element of the vector which is a pointer) itself. It can be the element itself by using

for(auto & it: ClassOne){
    it -> MyMethod();
}

instead. but this is not optimal here.

Please, note that it's not recommended to use plain pointers. use smart ones instead.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206667

When you use,

for(auto it: ClassOne)
{
   // ...
}

it is a MyClass*, not an an int. Hence you need to change the call to MyMethod to

it->MyMethod();

The for loop needs to be:

for(auto it: ClassOne)
{
   it->MyMethod();
}

Upvotes: 2

Related Questions