Situation:
class Person {
public:
int& age();
int age() const;
private:
int m_age;
};
I don't know if this works as I think, so my first question is this:
Example:
Person p;
p.age() = 15; //first method is called?
std::cout << p.age(); //second method?
I'm starting to think that this is full of stupidity which is based on mixing operator overloading and const methods, so please: could somebody enlighten me? :D
If miraculously this works, can I use this instead of getters & setters or this is a bad exercise?
Yes and no.
Properties are syntactic sugar for hiding functions. So yes. You can write a function that returns a reference and get something that, on the surface, looks like a property.
But consider this: behind the property is a setter function that can (and should) do more than simply set a value. The point of any setter is to ensure that setting the value does not harm the state of the object.
By replacing the setter with a function that returns an unprotected reference to a private
member you are stripping away this line of defense. The caller can use that reference as they see fit and to the possible detriment of the object. This might be just fine, depending on the nature of the member, but you might as well be honest. Declare the member public
, improve readability, and save yourself the hassle of writing the function.
As for the const
part of the question, you can sort of (and this is an ugly, simplistic sort of "sort of") think of int& age()
as int& age(Person * this)
and int age() const
as int age(const person * this)
In OP's example, age()
is never invoked on a constant Person
, so there is no reason for int age() const
to ever be invoked.