RobeeZ
RobeeZ

Reputation: 95

c++ - automatic casting with derived class

I have a class called Action, and a MoveAction which derives from Action and I have an object which holds a variable: Action action_to_perform. Now I assigned a new MoveAction to this variable. These Action classes holds a method perform(). MoveAction does something else than Action's perform. When I call

object->action_to_perform

then it calls Action's perform method, when it's set to a MoveAction object. How can I automatically cast it a MoveAction?

EDIT:

Action.h:

class Action
{
public:
    Action();
    virtual ~Action();

    virtual void perform();
protected:
private:
};

MoveAction.h:

class MoveAction : public Action
{
public:
    MoveAction(int, int);
    virtual ~MoveAction();

    int dx, dy;

    virtual void perform();
protected:
private:
};

In Player.cpp:

Action action_to_perform;
...
action_to_perform = MoveAction(0, 1);

Upvotes: 1

Views: 1130

Answers (1)

R Sahu
R Sahu

Reputation: 206557

You are experiencing the problem of object slicing.

You need to store a pointer to Action.

Action* action_to_perform = NULL;
...
action_to_perform = new MoveAction(0, 1);
action_to_perform->perform();

should work.

To simplify memory management, it is better to store a smart pointer, such as shared_ptr or unique_ptr.

std::unique_ptr<Action> action_to_perform;
...
action_to_perform.reset(new MoveAction(0, 1));
action_to_perform->perform();

Upvotes: 3

Related Questions