In my game engine I have a State class that represents the game world at a point in time. This State contains a number of Body objects that define one rigid body each. Each State has a container to keep track of the Body objects it owns, and each Body has a pointer back to its parent State.
Outline of State class:
class State {
private:
std::set<Body*> _bodies;
public:
//It could be done here
void addBody(Body* body) {
//Remove from old State
if (body->_state)
body->_state->_bodies.erase(this);
//Set Body's back-reference
body->_state = this;
//Add to this State
_bodies.insert(body);
}
};
Outline of Body class:
class Body {
private:
State* _state;
public:
//It could also be done here
void setState(State* state) {
//Remove from old State
if (_state)
_state->_bodies.erase(this);
//Set back-reference
_state = state;
//Add to the new State
if (_state)
_state->bodies.insert(this);
}
};
The problem, if there is one, is that adding/removing a Body to/from a State requires changing a private member of each.
At one point I considered having a State-Body-mediator static class, which would have friend access to both classes. It sounds nice, because the State-Body relationship would be explicitly managed by that name, but it's a lot of declaration overhead for managing a simple relationship.
Is there a "better" way to do this? I'd like to see what kinds of ideas are out there.