Search code examples
c++design-patternsstate-pattern

C++ State pattern exception


I'm new in c++! Please help me to implement State pattern.

I have the code below, but it doesn't compile:

class MasterThreadState;
class Init; class Idle;

class MasterThread
{
public:
    MasterThread(){
        _state = Init::State();
    }
    void handle(int sender, int tag);
private:
    int _sender;
    MasterThreadState* _state;
private:
    friend class MasterThreadState;
    void goTo(MasterThreadState* newState){ _state = newState; }
};

class MasterThreadState
{
public:
    virtual void recieved(MasterThread& master, int tag);
protected:
    void goTo(MasterThread& m, MasterThreadState* newState){
        m.goTo(newState);
    }
};

class Init : MasterThreadState {
public:
    static MasterThreadState& State() { return instance; }
    virtual void recieved(MasterThread& master, int tag);
private:
    static Init instance;
};

class Idle : MasterThreadState {
public:
    void recieved(MasterThread& master,int tag);
    static MasterThreadState& State(){ return instance; }
private:
    static Idle instance;
};

The error is:

incomplete type 'Init' used in nested name specifier _state = Init::State();


Solution

  • The virtual function wasn't implemented

    This code work's fine:

    class MasterThreadState;
    class Init; //class Idle;
    
    class MasterThread
    {
    public:
        MasterThread();
        void handle(int sender, int tag);
    private:
        int _sender;
        MasterThreadState* _state;
    private:
        friend class MasterThreadState;
        void goTo(MasterThreadState* newState){ _state = newState; }
    };
    
    class MasterThreadState
    {
    public:
        virtual void recieved(MasterThread& master, int tag) = 0;
    protected:
        void goTo(MasterThread& m, MasterThreadState* newState){
            m.goTo(newState);
        }
    };
    
    class Init : MasterThreadState {
    public:
        static MasterThreadState* State();
        virtual void recieved(MasterThread& master, int tag);
    private:
        Init(){}
    };
    
    class Idle : MasterThreadState {
    public:
        static MasterThreadState* State();
        virtual void recieved(MasterThread& master,int tag);
    private:
        static Idle instance;
    };