Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling this->get/this->set methods versus directly accesing member variables in C++

Tags:

c++

Suppose I have a class Foo, with a private variable bar_ containing some state for Foo. If necessary, I may write public get/set methods for bar_. Naturally, I avoid this as much as possible to maintain encapsulation.

Assuming I have these get/set methods, whenever I have to access or modify bar_ within a method belonging to Foo, I usually do it directly to bar_, instead of using the get/set methods, which I use for accessing bar_ from outside the class. I have no justification other than concerns regarding the speed of directly accessing the variable versus calling the methods, but I suspect that if the get/set methods are defined inline (which they are) it shouldn't make a difference. Does it make a difference? Does constness play a role in this?

So far I haven't had any problems with this, but I have a lingering feeling I am Doing It Wrong. Are there any compelling arguments for not doing it? Any guidelines regarding this?

like image 936
dimatura Avatar asked Mar 03 '10 18:03

dimatura


1 Answers

I know it is close to herecy, but I hate get/set methods. Loathe them. Almost never write them.

Generally, a class should either provide much more high-level operations than directly and simply reading and modifying internal state variables, or it should get out of the way and act like the struct it is.

Even if I were to write one, I would almost never use it inside the class. The whole point of them is that you can change the internal representation of thing without affecting a client. Inside the class, it is the internal representation you care about! If you are tempted to do a lot of operations on the class using its own interface inside the class, you probably have a second class in there fighting to get out.

like image 152
T.E.D. Avatar answered Oct 05 '22 15:10

T.E.D.