There are a lot of different mechanisms to track changes of an object.
The first alternative is to use indeed observers. This implies that every method that changes data in your object, calls the observers. In practice it's best to put this in one function, like this:
class MyClass { public: void setValue(int value) { m_value = value; notifyObservers(); } private: void notifyObservers() { for (auto it=m_observers.begin();it!=m_observers.end();++it) (*it)->notify(this); } std::list<Observer *> m_observers; };
An alternative is to store whether the object has been changed. However, this requires you to define the meaning of "has been changed"; in other words: when do I reset the 'changed' flag. An easy solution is to use a version number. Whenever the object changes, you increase the version number, like this:
class MyClass { public: void setValue(int value) { m_value = value; ++m_version; } int getVersion() const { return m_version; } private: int m_version; };
Now other classes can simply request the version number and use it to see whether it has been changed since they last asked for the version number.
Both approaches have their advantages and disadvantages:
- In the observer mechanism, changes can be slow (since you need to call all observers), but you are guaranteed that all observers will be immediately up-ot-date
- In the version-number approach, changes are very fast, but you rely on the other classes to regularly query your class for changes
Which mechanism is the best in your case depends on the situation. If found that in practice it's best to mix them, depending on the situation. Some changes are best propagated immediately (e.g. in calculations), other changes are best delayed (e.g. updating your screen).