my question is, submachine is a member of FSM, so it should have access to local instances of all the attributes of FSM, no?
No. Unlike in Java, inner class objects don't have an implicit reference to an outer object.
wouldn't we be creating an intance of all its members i.e. submachine?
submachine
is a type, not a member variable. If you wanted a member variable, you'd have to do something like this:
struct FSM {
struct submachine {
...
};
submachine sm; // Member variable of type submchine
};
And if you want sm
to "see" its parent object, you'll need to pass it explicitly:
struct FSM {
struct submachine {
FSM &parent; // Reference to parent
submachine(FSM &f) : parent(f) {} // Initialise reference in constructor
};
submachine sm;
FSM() : sm(*this) {} // Pass reference to ourself when initialising sm
};
Note that the same principle applies for instances of submachine
that aren't member variables. If you want them to be able to access an FSM
instance, you'll need to pass a reference to one.
Note also that you could use a pointer rather than a reference. In fact, a pointer offers greater flexibility in many cases.