Consider the following class:
class MyClass1 { public: double x() const {return _x;}
Since the actual content of MyClass1 is an implementation detail, getters and setters provide a single way to get and set the contents of the class, even if they are interdependent (here _z does not exist inside, and for the user, z is a variable of type x and y ).
Now, to avoid having to write getter / setter for x and y , you can use the wrapper as follows:
template <typename Type> class Wrapper { public: constexpr Wrapper(const Type& value) {_value = value;} constexpr Type& operator()() {return _value;} constexpr const Type& operator()() const {return _value;} constexpr void operator()(const Type& value) {_value = value;} protected: _value; };
And now the source class will look like this:
class MyClass2 { public: Wrapper<double> x; Wrapper<double> y; double z() const {return x*y;}
Is this a dangerous practice or a good solution to avoid having to write getters / setters?
Note. Here MyClass1 and MyClass2 are just examples. My question is very "general": is it dangerous to replace getters / setters of classes with the proposed Wrapper when the getter / setter just returns / sets the internal value.
source share