Path: csiph.com!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: Fri, 23 Aug 2019 05:26:05 -0700
Organization: A noiseless patient Spider
Lines: 58
Message-ID: <86tva8131e.fsf@mailhub.linuxsc.com>
References: <86y2zk26ps.fsf@mailhub.linuxsc.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="3dc9dd473b90ddbbb978ff4dade5239c"; logging-data="12266"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18a9H/f9LUPZQcuItZgQG3sC0zt5BcvuJ0="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:5jti1hIHZN2Vd/eM8rbuMtq2P0g= sha1:pSyDM8yuolSbiuF2m56NNxUwN1o=
Xref: csiph.com comp.lang.c++:67904
Ian Collins writes:
> On 23/08/2019 10:09, Tim Rentsch wrote:
>
>> 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.
>
> There is a case where a data member is safe to be public: a const
> data member. Access to such a member cannot change a class's
> invariants.
My experience with const data members is that they are almost
always more trouble than they're worth. Even in those cases
where a data member is made const, it's better to stick to the
simple rule that data members (other than pure structs) never be
public, on general principles of information hiding: client code
shouldn't know or care what particular data members a class has,
let alone whether they are const or not. Any property an object
wants to supply to its clients should be made available through a
(usually const) member function, and only that, regardless of
whether the property needs an elaborate computation or is simply
returning the value of a data member -- even a const one.