In C#, there is a nice syntax sugar for fields with getter and setter. Moreover, I like the auto-implemented properties which allow me to write
public Foo fo
You can emulate getter and setter to some extent by having a member of dedicated type and overriding operator(type)
and operator=
for it. Whether it's a good idea is another question and I'm going to +1
Kerrek SB's answer to express my opinion thereon :)
I collected the ideas from multiple C++ sources and put it into a nice, still quite simple example for getters/setters in C++:
class Canvas { public:
void resize() {
cout << "resize to " << width << " " << height << endl;
}
Canvas(int w, int h) : width(*this), height(*this) {
cout << "new canvas " << w << " " << h << endl;
width.value = w;
height.value = h;
}
class Width { public:
Canvas& canvas;
int value;
Width(Canvas& canvas): canvas(canvas) {}
int & operator = (const int &i) {
value = i;
canvas.resize();
return value;
}
operator int () const {
return value;
}
} width;
class Height { public:
Canvas& canvas;
int value;
Height(Canvas& canvas): canvas(canvas) {}
int & operator = (const int &i) {
value = i;
canvas.resize();
return value;
}
operator int () const {
return value;
}
} height;
};
int main() {
Canvas canvas(256, 256);
canvas.width = 128;
canvas.height = 64;
}
Output:
new canvas 256 256
resize to 128 256
resize to 128 64
You can test it online here: http://codepad.org/zosxqjTX
Based on https://stackoverflow.com/a/23109533/404734 here is a version with a public getter and a private setter:
struct Foo
{
class
{
int value;
int& operator= (const int& i) { return value = i; }
friend struct Foo;
public:
operator int() const { return value; }
} alpha;
};