I'm trying to use virtual methods in C++.
I have an objects hierarchy:
class Action {
public:
Action() { }
virtual void action() = 0;
}
class CubeAction : public Action {
public:
CubeAction() { }
void action() {
glutSolidCube(1);
}
};
And I have a container for objects of the base class.
class ActionContainer {
private:
std::vector<Action *> actions;
public:
void add(Action &action) { actions.push_back(&action); }
void doActions() {
for (auto a : actions) {
a->action();
}
}
};
And when I try to doActions
:
ActionContainter actions();
CubeAction cubeAction();
actions.add(cubeAction);
actions.doActions();
I get pure virtual method called
error.
I used the Calling a virtual function on a vector of base classes solution, but error still happened.
UPD: sorry, that is my real code: Github. Some bug in Action.h
file, I think.
Your code in github looks like this:
try {
SphereAction sphereAction(1);
actions.add(sphereAction);
CubeAction cubeAction(2);
actions.add(cubeAction);
} catch (InfoException e) {
cerr << e.what() << endl;
}
and afterwards, you call display()
, which calls ActionContainer::doActions()
.
In the container, you store a pointer to the argument, but you pass a local variable to actions.add()
, which will be out of scope and no longer exist when it is used.