class OSwitch {
private:
Operator *operators[];
//int variable; <-- unused variable
public:
OSwitch() {}
~OSwitch() {}
void setOperator(int id, Operator *op) {
operators[id] = op;
}
void execute(int id) {
operators[id]->execute();
}
};
There are several subclasses of the abstract baseclass Operator.
When calling setOperator() for more than one time, the array “forgets” the last element.
for example
XOperator a;
YOperator b;
os.setOperator(1,a);
os.setOperator(2,b);
os.execute(1); // <- wont work
But when the int variable (or any other variable in OperatorSwitch) is declared, it works.
I dont have any idea how this works.
Thanks for any hint.
Your member variable
operatorsis an unsized array, which is an incomplete type and not allowed in a class definition.What you probably want instead is a map of integers to pointers:
Note that it will be an error to call
executeon an ID that has not been assigned a valid pointer. You can make this more robust by checking for existence of the map element first.