1

This is the situation: a Player class with statistics as variables. a Keeper class derived from Player.

an Action class a Run class derived from Action

the player class has vector<Action*>

I don't understand how i can implement the following functionality: iterate through the vector and based on the action, update the correct attribute in Player or Keeper (numberOfRunKm and numberOfSaves)

class Action {
public:
    Action();
    virtual ~Action();
    virtual void write();
};

class Run: public Action {
    double runKm;
public:
    Run(double runKm);
    ~Run();
    double getRunKm() const;
    void setRunKm(double runKm);
    void write();
};

class Save: public Action  {
public:
    Save();
    ~Save();
    void write();
};

class Player {
    string name;
    vector<Action*> actions;
    double numberOfRunKm = 0.0;
public:
    Player(const string &name);
    ~Player();
    virtual void write();
    void run();
    void addAction(Action* action);
    void updateStatistics();
};

class Keeper: public Player {
    int numberOfSaves = 0;
public:
    Keeper(const string &name);
    ~Keeper();
    void write();
    void save();
};
  • 1
    Well, I would think that when I "don't understand how i can implement" something in C++, the first place I would look would be [a good C++ textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? What about the C++ programming language, exactly, you don't understand? Sounds like you need to implement a virtual method. Do you know what virtual methods are, how they work, and how to use them? – Sam Varshavchik Nov 16 '20 at 21:23
  • the only virtual method is write(), so you can not do anything else. Eventually you can "hack" and determine the real class at runtime, but I do not advice it, unless this is the goal of the exersise. – Nick Nov 16 '20 at 21:35
  • thank you for the quick replies, I could use a virtual function in Action and then override it in the derived classes, then I would be in the correct class. But there's where my problem lies, I can't see a way to increment numberOf RunKm with the runKm of Run – Frederik Callens Nov 16 '20 at 21:46
  • A player creates a new action when the player is aware of that action (i.e. inside the `run()` method. The player decides to add a run action, while knowing the kilomters run and uses that information to create the run action. The player also uses the same information to update the player objects attribute of `numberOfRunKm`. There is hence no need to get the info from the action object. The info goes into that object (at creation) instead of needed to come out of it. – Yunnosch Nov 16 '20 at 22:03

0 Answers0