Arduino project. Using C++ 11 compiler. I have created an "interface" class, and several implementation classes. I want to implement stategy pattern. In my strategy manager class, I want to create an array of fixed length and initialize it in the constructor.
Java example of what I'm trying to do (and should be piece of cake in any modern language, right Stroustrup?)
public interface IState {
public void handle();
}
public class StateImpl implements IState {
@Override
public void handle(){
//Do something
}
}
public class StrategyManager {
private IState[] states;
public StrategyManager(){
states = new IState[3];
state[0] = new StateImpl();
state[1] = new StateImpl();
...
}
}
My first attempt in C++:
IState.h:
class IState {
public:
virtual ~IState() {}
virtual void handle() = 0;
};
StateImpl.h:
#ifndef StateImpl_h
#define StateImpl_h
#include "IState.h"
class StateImpl : public IState {
public:
StateImpl();
virtual void handle() override;
};
#endif
StateImpl.cpp:
#include "StateImpl.h"
StateImpl::StateImpl(){}
void StateImpl::handle(){
//Do something
}
So far it's ok. I've simplified my classes for brevity so the code might not compile, but mine's does, Now here comes the problem:
StrategyManager.h:
#ifndef StrategyManager_h
#define StrategyManager_h
#include "IState.h"
class StrategyManager {
private:
extern const IState _states[3];
public:
StrategyManager();
};
#endif
StrategyManager.cpp:
#include "StrategyManager.h"
StrategyManager::StrategyManager(){
IState _states[3] = {
new StateImpl(),
new StateImpl(),
new StateImpl()
};
}
This gives me all sort of errors:
error: storage class specified for '_states'
error: invalid abstract type 'IState' for '_states' because the following virtual functions are pure within 'IState':
virtual void IState::handle()
error: cannot declare field 'StrategyManager::_states' to be of abstract type 'IState'
since type 'IState' has pure virtual functions
... etc
So I have changed the array to hold pointers instead. In StrategyManager.h:
extern const IState* _states[3];
And now in StrategyManager.cpp constructor:
StrategyManager::StrategyManager(){
IState impl = new StateImpl(); //I hope this will be stored in the heap.
IState* _states[3] = {
&impl,
&impl,
&impl
};
}
But still got errors:
error: storage class specified for '_states'
error: cannot declare variable 'impl' to be of abstract type 'IState'
since type 'IState' has pure virtual functions
And on and on and on...
How can I do this in a simple way without using vectors or boost or any other fancy stuff? (Remember this is Arduino)