Re: References
Andrea Crotti <andrea.crotti.0@gmail.com> wrote in
news:m1d3qabwg4.fsf@ip1-201.halifax.rwth-aachen.de:
Pete Becker <pete@versatilecoding.com> writes:
Ok very good now is more clear...
Which brings me to the next question.
Suppose I have the situation above, and the Packer also keeps an
alternative representation of the object.
There are basically two different approaches. Decide who's in charge:
either the Packer notifies the Packet that the value has changed, or
the Packet can ask the Packer whether the value has changed.
Continuing the silly example
Get rid of shared data between classes and use proper encapsulation -
this will save many headaches in long turn. All data should be private
unless your class is just a bundle of unrelated stuff like std::pair.
Example:
class Packer
{
public:
Packer(int _x) : x(_x), dirty(true) {}
private:
int x;
bool dirty;
public:
void packData(char *) {
if (dirty)
// do something
dirty = false;
}
void NotifyXChanged(int new_x) {
x = new_x;
dirty = true;
}
int GetX() const {return x;}
};
class Packet
{
public:
Packer p;
void setX(int _x) {
p.NotifyXChanged(_x);
}
Packet(int _x) : p(x) {}
int GetX() const {return p.GetX();}
};
int main() {
Packet p1(10);
cout << p1.GetX() << endl;
p1.setX(3);
cout << p1.GetX() << endl;
return 0;
}
hth
Paavo