C++ syntax, calling a class member

In the following code example of the State Design Pattern, in the main code at the bottom it defines an instance of class Machine, and then calls Machine::off;. Why doesn't it instead call fsm.off;?
1
2
3
  Machine fsm;

  Machine::off;

Then I tried imitating that by adding a class Abba, and then doing:
1
2
  Abba a;
  Abba::DoStuff();

but that didn't work. Why?

Full code example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// StatePattern.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
class Machine
{
  class State *current;
  public:
    Machine();
    void setCurrent(State *s)
    {
        current = s;
    }
    void on();
    void off();
};

class State
{
  public:
    virtual void on(Machine *m)
    {
        cout << "   already ON\n";
    }
    virtual void off(Machine *m)
    {
        cout << "   already OFF\n";
    }
};

void Machine::on()
{
  current->on(this);
}

void Machine::off()
{
  current->off(this);
}

class ON : public State
{
  public:
    ON()
    {
        cout << "   ON-ctor ";
    };
    ~ON()
    {
        cout << "   dtor-ON\n";
    };
    void off(Machine *m);
};

class OFF : public State
{
  public:
    OFF()
    {
        cout << "   OFF-ctor ";
    };
    ~OFF()
    {
        cout << "   dtor-OFF\n";
    };
    void on(Machine *m)
    {
        cout << "   going from OFF to ON";
        m->setCurrent(new ON());
        delete this;
    }
};

void ON::off(Machine *m)
{
  cout << "   going from ON to OFF";
  m->setCurrent(new OFF());
  delete this;
}

Machine::Machine()
{
  current = new OFF();
  cout << '\n';
}


class Abba
{
  public:
    void DoStuff(State *s)
    {
        cout << "Doing Stuff" << endl;
        
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
  Machine fsm;

  Machine::off;
  Machine::on;

  Abba a;
  Abba::DoStuff();
}
1
2
3
4
5
6
7
8
9
10
11
int main(int argc, char* argv[])
{
    Machine fsm;
    fsm.off();
    fsm.on();

    Abba a;
    Abba.DoStuff();

    return 0;
}


@L B, You're right.
Last edited on
@kbw missing function call parameter list on lines 4 and 5, the code does nothing.
void DoStuff(State *s) here you say that you are going to pass a parameter, so when you call that function you must pass a parameter
1
2
3
State Empire;
Abba Fernando;
Fernando.DoStuff( &Empire );


1
2
3
4
5
6
    void on(Machine *m)
    {
        cout << "   going from OFF to ON";
        m->setCurrent(new ON());
        delete this;
    }
o_O
By the way, your last state will leak.
Topic archived. No new replies allowed.