3

I have a class representing the state of my application and I want to create many commands to update this state.

class State{ private: list<int> intList; ... } class ICommand { public: virtual ~ICommand(){} virtual void execute(State* state) = 0; } 

ICommand implementations will specify how to update the state, so they should interact with its private fields.

My problem is: what is the best approach in C++ to let commands update the private field of State?

If I expose intList with a public getter I can't guarantee that only commands update the state.

If I would use class friendship I have to link State with command implementation because linking it with the interface does not work and it seems to me not so good...

Is my doubt about 'friendship' unfounded? Should I choose a different approach?

1 Answer 1

0

In this case, using friend declarations is a good choice.

These conditions often arrive with implementations of some design patterns like command, state machine, and strategy. I think of these patterns as extensions of the class holding the state. That is if it was practical, ICommand would be part of the State class. That means using friend in C++.

In many of these cases, I go further and make ICommand a nested class within State, clearly indicating that these classes are tied together.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.