One more advantage is that it abstracts away the storage of the data. For example, let's suppose you're implementing the edit control of a cross-platform GUI library. Among many other things, you have a background colour for the control.
How do you get and set it? In the Win32 implementation, you'd have a color member and use it to intercept and handle WM_CTLCOLOREDIT. (If there is such a thing...) The Win32 edit control doesn't store its own colour, it requires the user to set it every time the edit needs to redraw itself.
So, you'd have the interface like this:
Code:
class Edit {
public:
colortype color;
};
And then people can set this color member and the color changes.
Well, first case for the setter is that it doesn't change. The color won't change until a redraw, which means that the user would still have to call Redraw(). But with a setter, you can do that yourself:
Code:
class Edit {
colortype color_;
public:
colortype getColor() { return color_; }
void setColor(colortype color) { color_ = color; redraw(); }
};
Then you're porting the whole thing to, say, Gnome and want to use GTK widgets. Now, a GTK edit control, if I recall correctly, does store its own color information, so suddenly your member becomes redundant.
What you can do then is to change the privates:
Code:
class Edit {
gtk_widget *widget_;
public:
colortype getColor() { return gtk_get_color(widget_); }
void setColor(colortype color) { gtk_set_color(widget_, color); }
};
Just one of many advantages.