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
C++ doesn't have this built in, you can define a template to mimic properties functionality:
template
class Property {
public:
virtual ~Property() {} //C++11: use override and =default;
virtual T& operator= (const T& f) { return value = f; }
virtual const T& operator() () const { return value; }
virtual explicit operator const T& () const { return value; }
virtual T* operator->() { return &value; }
protected:
T value;
};
To define a property:
Property x;
To implement a custom getter/setter just inherit:
class : public Property {
virtual float & operator = (const float &f) { /*custom code*/ return value = f; }
virtual operator float const & () const { /*custom code*/ return value; }
} y;
To define a read-only property:
template
class ReadOnlyProperty {
public:
virtual ~ReadOnlyProperty() {}
virtual operator T const & () const { return value; }
protected:
T value;
};
And to use it in class Owner:
class Owner {
public:
class : public ReadOnlyProperty { friend class Owner; } x;
Owner() { x.value = 8; }
};
You could define some of the above in macros to make it more concise.