I'm really new to C++ and one of the first things that has me really stumped is how to write a getter/setter that can use dot notation to get at a property.
For instance, instead of:
myObj.getAlpha();
it would be
myObj.alpha;
Is using dot notation like this frowned upon in C++ or is it just a pain to setup? I've had a hard time tracking down examples that weren't totally over my head so any guidance is much appreciated!
You can actually implement a getter and setter to a field like
myObj.alpha
but that is hard to setup and requires a proxy class.
The way for doing this is:
template<typename T>
class SetterProxy
{
T *m_T;
public:
SetterProxy(T &property) : m_T(&property) { }
SetterProxy(const SetterProxy&) = delete;
SetterProxy operator =(const SetterProxy&) = delete;
operator T&()
{
return *m_T;
}
T &operator =(T &other)
{
*m_T = other;
return *m_T;
}
}
class MyClass
{
int m_alpha;
public:
SetterProxy<int> alpha;
MyClass() : alpha(m_alpha) { }
}
"Properties" in other programming languages are mostly a quick shorthand - a superficial shorthand for a pair of function calls. The other benefits (like metadata) don't really exist in C++. You have the following options:
getProperty()
and setProperty()
pair of functions.I would suggest going with the simplest option for you, without giving up type safety & encapsulation. As long as the compiler still prevents external classes from messing things up in your class, public member variables are fine.
Consider accessing the property using the proposed notation.
alpha
is obviously a member of the class, let's say of type member_t
. Let's also say that the property you intend to add is of type prop_t
. Now if member_t
is the same as prop_t
you haven't really made a property because you have provided free access to the underlying member, so let's assume that member_t
is different from prop_t
.
It then follows that member_t
must have an implicit conversion to prop_t
(which is doable, but usually frowned upon).
It also means that member_t
must override the assignment operator to store the value provided to it when you set it.
Finally, you have to add getter and setter methods to the class which implement the get/set logic, and have member_t
aggregate pointers to these functions as members (so that it can call the getter inside the implicit conversion to prop_t
and call the setter inside the overridden assignment operator).
All of the above is certainly doable, but why would you want to write all this code? There is no tangible benefit at all, and doing it just for the sake of making C++ look like a language it is not won't earn you much support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With