[SOLVED] State Design Pattern



  • I'm curious about something that I've started to look at (and ponder) - Finite State Machines. I've been looking at some of the hits returned by different searches to understand how they work and the method used to implement them seems a little confused.

    The implementations that I have read through/dissected all seem to implement a weird sort of circular reference between the State abstract class (and any classes based on the State class) and the Player class. How can the c++ compiler handler this sort of implementation. As near as I can tell, to compile the State abstract class, the compiler must have knowledge of the Player class; but, to compile the Player class, it must first compile the State abstract class. I've put a general sort of outline of what I've been seeing below.

    I'm sure that something very fundamental is escaping me.

    @

    class State
    {
    public:
    virtual void Enter(player*);
    virtual void Execute(player*);
    virtual void Exit(player*);
    }

    class Player
    {
    private:
    State* m_pCurrentState;

    }

    @



  • @
    class Player;
    class State
    {
    public:
    virtual void Enter(Player*);
    virtual void Execute(Player*);
    virtual void Exit(Player*);
    }

    class Player
    {
    private:
    State* m_pCurrentState;

    }@



  • It is called forward declaration to solve circural references. It is commonly used in Qt applications' header files for types.



  • Consider the code posted by ixSci. When the compiler sees the line 1 it understands, that you are going to use Player type. It is not clear how it is defined and what it looks like, but it is going to find out that later. I would say that forward declarations are used almost everywhere. Another way of using it is to reduce includes in header files, i.e. if you declare a function in a header like:

    @void func(CustomType *iParam);@

    and CustomType is defined in CustomType.h, then it is better to do a forward declaration like
    @
    class CustomType;
    void func(CustomType *iParam);@

    rather than including its header like:
    @
    #include <CustomType.h>

    void func(CustomType *iParam);@



  • Just a bit of adjustment: Forward declaration can be used when the size of a type is not necessary at the moment of a compilation i.e. forward declaration can be used with pointers and references only because its size is predetermined.
    The "link":http://www.goingware.com/tips/parameters/notrequired.html seems to be appropriate but I didn't read it myself



  • Thanks! Just finished reading up on Forward Declarations. Interesting stuff.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.