Problem with Command Pattern under Visual Studio 2008 (C++)
- by D.Giunchi
Dear All,
I've a problem with this pattern under c++ on VS 2008.
The same code has been tested in gcc (linux, mac and mingw for
widnows) and it works.
I copy/paste the code here:
class MyCommand {
public:
virtual void execute() = 0;
virtual ~MyCommand () {};
};
class MyOperation {
public:
virtual void DoIt() {}; //I also write it not inline
};
class MyOperationDerived : public MyOperation {
public:
virtual void DoIt() {}; //I also write it not inline
};
class MyUndoStackCommand : public MyCommand {
public:
typedef void(MyOperation::*Action)();
MyUndoStackCommand(MyOperation *rec, Action action);
/*virtual*/ void execute();
/*virtual*/ ~MyUndoStackCommand();
private:
MyOperation *myReceiver;
Action myAction ;
};
in cpp:
#include "MyUndoStackCommand.h"
#include "MyOperation.h"
MyUndoStackCommand::~MyUndoStackCommand() {
}
MyUndoStackCommand::MyUndoStackCommand(myOperation *rec, Action
action): myReceiver(rec), myAction(action) {
}
void MyUndoStackCommand::execute() {
((myReceiver)->*(myAction))();
}
use in main.cpp:
MyReceiver receiver;
MyUndoStackCommand usc(&receiver, &MyOperation::DoIt);
usc.execute();
when I debug under visual studio only if I set inside MyUndoStackCommand, directly
myAction = &MyOperation::DoIt , it works, otherwise not.
Any advice?
thank you very much,
dan
Edit: The following code compiles with g++ - changes by Neil Butterworth flagged as //NB.
class MyCommand {
public:
virtual void execute() = 0;
virtual ~MyCommand () {};
};
class MyOperation {
public:
virtual void DoIt() {}; //I also write it not inline
};
class MyOperationDerived : public MyOperation {
public:
virtual void DoIt() {}; //I also write it not inline
};
class MyUndoStackCommand : public MyCommand {
public:
typedef void(MyOperation::*Action)();
MyUndoStackCommand(MyOperation *rec, Action action);
/*virtual*/ void execute();
/*virtual*/ ~MyUndoStackCommand();
private:
MyOperation *myReceiver;
Action myAction ;
};
MyUndoStackCommand::~MyUndoStackCommand() {
}
MyUndoStackCommand::MyUndoStackCommand(MyOperation *rec, //NB
Action action)
: myReceiver(rec), myAction(action) {
}
void MyUndoStackCommand::execute() {
((myReceiver)->*(myAction))();
}
int main() {
MyOperation receiver; //NB
MyUndoStackCommand usc(&receiver, &MyOperation::DoIt);
usc.execute();
}