Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Ian Collins Newsgroups: comp.lang.c++ Subject: Re: About getters/setters Date: Fri, 23 Aug 2019 16:17:00 +1200 Lines: 47 Message-ID: References: <86y2zk26ps.fsf@mailhub.linuxsc.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net ADzKyCrQOq6uzjrdVNoedA8D7asHXA/Eoovo6inpt8tz1FbMpE Cancel-Lock: sha1:tt5SelebzStdwyw/Za4OG/HuhPk= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.7.2 In-Reply-To: <86y2zk26ps.fsf@mailhub.linuxsc.com> Content-Language: en-US Xref: csiph.com comp.lang.c++:67897 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. -- Ian.