einpoklum
einpoklum

Reputation: 132222

Missing convention for C++ accessors?

I've read the community wiki quetion about the 3 different conventions for accessor methods and was supmetwhat surprised not to see the following convention:

const unsigned& amount() const { return _amount; }
unsigned& amount() { return _amount; }

true, it's not quite the same as seamless as being able to avoid the parentheses altogether () - which would (I feel) be idea - but it's still something; right?

Upvotes: 0

Views: 126

Answers (3)

James Kanze
James Kanze

Reputation: 154027

It defeats the purpose of accessors. If you provide the two functions, you might as well make the data member public and be done with it.

EDIT:

Just to make things perfectly clear: there are cases where using a C style struct is the most appropriate solution. In those cases, you make the data members public, and don't worry about accessors. For classes with significant behavior, on the other hand, you won't have accessors at all, or very few. For the most part, the internal state is not reflected directly at the public interface (and that state which is is usually read only). About the only time you'd have need for accessors is for classes which are basically data, but which must enforce invariants across the data,

(And for what it's worth: if the data is logically an attribute of the class, I use:

int amount() const { return myAmount; }
void amount( int newValue ) { myAmount = newValue; }

For getters of values which are not logically attributes, however, I'll use getAmount().)

Upvotes: 8

Zeenobit
Zeenobit

Reputation: 5204

The problem with this is that it can defeat the purpose of a getter/setter convention. If you're passing a mutable reference to the private member, you might as well expose the member and remove the hassle of function calls.

Also, I found this syntax very ugly and unreadable, but that's my personal taste:

foo.amount() = 23;

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129524

The second of your examples gives the user access to the original _amount in the class, without any form of protection from the class itself. The purpose of "encapsulation", which is an important aspect of OOP is to ensure that all the accesses to a variable is done within the class itself - that way the class can control the value range or other validity.

If you want the class to transparently allow the user to use amount, then call it amount and make it public. There is no need for accessor functions then.

Upvotes: 2

Related Questions