0

I've built a class-based Push-down Automaton Finite State Machine. The context class (the class whose internal state is being modified) has some methods that only the states should access (incrementing/decrementing some iterators, pushing/popping states, setting an accepting state, etc). Right now they are public due to the different states needing access to them.

Would it be better to make the methods protected/private and define the states as friends of the context?

(nb4 "opinion-based!")

Casey
  • 10,297
  • 11
  • 59
  • 88

1 Answers1

1

It can be reasonable to make a collection of classes that work together for a common purpose friends, but there is one alternative you might consider.

For a really short, naive example:

class outer
{
 private:

 int a;
 int b;

 public:
 class inner
    { public:
      outer * o;

      inner( outer * io ) : o( io ) { o->a = 0; }

    };

};

int main(int argc, const char * argv[]) 
{
 outer o;
 outer::inner i( &o );

 return 0;
}

I did this quickly, so the construction of inner taking a pointer isn't really good C++, so don't take THAT as advice.

The point is that this compiles even though inner is accessing private members of outer.

That's another way of doing what you've asked.

JVene
  • 1,611
  • 10
  • 10
  • This solution does not scale very well. Increasing the number of inner classes by a factor of 10 makes it unwieldy and hard to read. :( – Casey Oct 02 '15 at 17:03