i've seen in some sources that some classes have Getters and Setters even for public data members

class Example
int m_ID;

string m_Name;
int m_Age;

Example( );
~Example( );

void SetName( string nName )    { m_Name = nName; }
void SetId( int nID )           { m_ID = nID; }
void SetAge( int nAge )         { m_Age = nAge; }

int GetID( )                    { return m_ID; }
int GetAge( )                   { return m_Age; }
string GetName( )               { return m_Name; }

well, i see relevance in creating functions to access private data( m_ID in this case ), but i don't know why would someone loose time for declaring fuctions for public data members

and also, isn't faster to access direclty the member rather than through a function?

Example ex;
ex.m_Age = 10;


Example ex;
ex.SetAge( 10 );

i suppose that the first example is faster since it doesn't call a function?..

and last question, why would i declare a data member private/protected if i need to access it?, making me have to write extra code for getters and setters; the only benefit i can see is that you cannot declare a pointer or a reference to the specific data member

Edited by dospy: n/a

6 Years
Discussion Span
Last Post by dospy

There are no hard and fast rules, but there are general guidelines. The overall theme is "give them what they need to do the job and no more than that". If they can't access it, they can't accidentally screw it up. They also don't ned to know or care about anything that goes on behind the scenes. If changing one variable forces some checking or changing some other variables or whatever, you don't want anyone who isn't thoroughly involved with the nuts and bolts of the code accessing/mutating it as they see fit. They whole thing's supposed to be as black of a box as possible, so you give Joe Schmo an API consisting of public methods and then he can't screw it up as much. That's good for you and it's good for Joe Schmo. It's the same reason they have covers on TVs. They don't want you manually adjusting any settings. They give the TV buttons and dials and a remote and that's all you get to play with!


thx for reply, but to be sure, is that an answer to the question "why to create functions to access data members?" or to "why would i declare a data member private/protected if i need to access it?"


I'm not sure the answer can be clearly pigeonholed into a single question. It's all one big topic that overlaps.

>> why would i declare a data member private/protected if i need to access it?

Define "you". Define "access". Are you the code writer? Or did I write it and you're using MY library in YOUR code. Doing it through functions gives you more control of who can change what when...

a, b, c, d, flag and updateParameters are all private. seta is public.

void someclass::updateParameters()
    d = /* some compilcated calculation involving a, b, c*/

void someclass::seta(int newa)
   if(!flag || newa > 10)

   a = newa;
   b = a + 5;
   c = 100 - a - b;
   // write this to a log file

Make it as complicated as you want. For the regular old "get" and "set" functions that are just one line functions, it may not matter as much. For systems where one variable closely relates to another and changing one needs to cause a chain reaction, it's more important.

A public getter for a public variable where all it does is return the variable probably doesn't make a lot of sense. Ditto with the setter.

Edited by VernonDozier: Cleaning up syntax


>>i've seen in some sources that some classes have Getters and Setters even for public data members
Remember that a large amount of open-source software is designed like a steaming pile of dog... Don't consider everything you see as "good practice" or as if the design choices they made were good, justified or even planned at all. This is true of roughly all programming languages with equal proportions: the amount of very poorly written open-source code far exceeds the amount of well-written open-source code. It doesn't mean that it is not _usable_, it just means that you shouldn't derive too many programming guidelines from the open-source code that you see.

>>I don't know why would someone lose time for declaring functions for public data members
Did you consider that maybe this didn't come at once? Maybe it used to be private/protected and used via get/set in many other functions of the software, then somebody decided that he preferred the data members to be public (a stupid decision IMO, but possible). Also, maybe there used to be more complex behaviour in the get/set functions (like bound-checking or mutex-locking) which was taken out after some testing or performance assessment, but the get/set were left such that the rest of the software would not need refactoring. There are plenty of other reasons why this might have happened (amongst them: just that the author is stupid). Real-world programming involves a lot of little issues, often related to maintenance, that make real-world code look quite a bit different from the ideal textbook cases (try to follow good textbook-like coding practices as much as possible, but eventually, you will break those guidelines in order to avoid complete rewrites or to repair past mistakes and salvage the code, etc. etc.).

>>isn't it faster to access directly the member rather than through a function?
In theory, yes, in practice, no. Many of the simple functions that are implemented in the class declaration will be inlined by the compiler, which means that instead of producing a function call, it just puts the body of the inline function into the body of whatever function is "calling" it. If inlined, the overhead of doing a function call disappears and, in this case, it boils down to the exact same code as if you accessed the data member directly. If your compiler doesn't do this, change your compiler for a decent one.

>>why would I declare a data member private/protected if I need to access it?
I think VernonDozier answered that pretty well already. I would just add that it often makes sense to put get/set functions for a private data member, even if it is trivial. Mainly, because you never know, if later, you would like to change the class' internals, without breaking all the code that uses it. For example, say I am making a class to represent a complex number. This is a trivial class that could very well have its data members public (Real and Imaginary values), but what if I later decide, that based on the kind of operations I do, that I would prefer to store the complex number of polar form (magnitude and argument). If I made the Real and Imaginary values public data members, then changing them to polar form would possibly destroy any code that uses this complex number class. But if I made the Real and Imaginary values accessible through get/set functions, then all I need to do to preserve the integrity of the software is to redefine those get/set functions in terms of the polar form. This is called encapsulation, and it is very important for maintainability because it handles two problems: "what if you want to add something or change something in the future" and "what if a programmer that uses the code or works on it has some 'genius' ideas and decides to temper with the guts of it".

Edited by mike_2000_17: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.