Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c++
Subject: Re: About getters/setters
Date: Thu, 22 Aug 2019 15:09:03 -0700
Organization: A noiseless patient Spider
Lines: 66
Message-ID: <86y2zk26ps.fsf@mailhub.linuxsc.com>
References:
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="3dc9dd473b90ddbbb978ff4dade5239c"; logging-data="2785"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+3hqR9mRnYXz78WcnDVp1PeHyBRlMb/bU="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:Ep/4bN8+3s3I2iOSioF3L3WtHpM= sha1:6bm7+6qxhyzOFzyDXfy7b5VeHaw=
Xref: csiph.com comp.lang.c++:67890
JiiPee writes:
[some white space reformatting done]
> Which one is better: 1)
>
> class Person {
> public:
> int getAge() { return age;}
> void setAge(int a) { age = a;}
> private:
> int age;
> };
>
> or 2)
>
> struct Person {
> int age;
> };
>
> ####
>
> I know Herb Sutter recommended 1) but for example isocpp
>
> https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-get
>
> seems to recommend 2). [...]
>
> I do currently 1) but wondering which way to go.
>
> Like now I have a "Settings" class. Simple data members. I started
> adding getters and setters....
I agree with Herb Sutter's recommendation that (assuming the
class or struct has some member functions) data members should
never be public. There are cases where for data members might
plausibly be made protected rather than private, but never
public. (Incidentally I am ignoring the "age/birthday" matter
that some other people have commented on, and assuming your
question is meant as generic, with 'age' being merely an
unfortunate choice of example.)
I suggest however a slightly different pattern than (1), along
these lines (disclaimer: not compiled):
class Person {
unsigned siblings_;
// ... other data members ...
public:
// ... other member functions
unsigned &siblings() { return siblings_; }
const unsigned &siblings() const { return siblings_; }
};
Now our accessor functions look more like data member access, but
they remain functions:
if( fred.siblings() > 0 ) ...
fred.siblings() += 1; // a new birth in fred's family
To me this pattern reads nicer on the client side than set/get
functions.