'Apply a superclass method on several instances with polymorphism by using pointers in C++

I have a superclass Athlete which provides a virtual void work() method, which is redefined in subclass Climber. I would like to create a big number of instances from the classes Athlete and Climber and apply to them the work() method, in just a couple of lines, thanks to polymorphism. I know, thanks to my searches, that it is possible with pointers, but I don't know how...

I know how to use pointers in order to apply the work() method on these instances, but only if I do that one by one like that:

class Athlete {
          .....
     virtual void work {
          cout << getName() << " is training very hard." << endl;
    }
};

class Climber: public Athlete{
      ......
    void work(){
        cout << getName() << " is climbing very hard." << endl;
    }
    .....
};


    Athlete athlete1 = Athlete(...);
    Climber climber1 = Climber(...);
            ....

    Athlete* a1 = &athlete1;
    Athlete* a2 = &climber1;
            ....

    a1->work();
    a2->work();     
            ....

But I don't know how to use a for-loop to automatically do that for thousands of instances for example. Can someone help me to do that?

Thanks in advance.



Solution 1:[1]

For those who are interested in a concrete solution and come on this page, here is one.

Thanks to the comments under my question, I was able to improve my searches on this topic and found a solution. I don't know if it is the perfect solution for my problem but at least, it works.

Here is the solution:

...

#include <vector>
....

int main(int argc, char* argv[]){

// Create a vector of pointers:
    vector<Athlete*> team;

// Call constructors to create instances:
    Athlete athlete1 = Athlete(...);
    Climber climber1 = Climber(...);
    Athlete athlete2 = Athlete(...);
    Climber climber2 = Climber(...);

// Fill the vector with pointers on instances:
    team = {&athlete1,&athlete2,&climber1,&climber2};

// Apply the work method() on every instances:
    for (Athlete * &i : team) 
    {
        i->work();
    }

    return 0;
}

Maybe someone can give me some improvement suggestions, and probably about the filling of the "team" vector, or about anything else.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jejouze