Hi all
I have a little question... Is there any advantage using:
var_x = MyClass.x;
instead of:
var_x = MyClass.Get_X();
Of course you can't access to a private var, but I wonder if it is worth to declare it as public and access it directly.
Any idea?
"It's only a bit, it can't hurt you..."
--------------------------------------- "It's only a bit, it can't hurt you..."
The answer to your question is really dependent on the context in which it is used.
For example...
public class Point { public int x; public int y; }
It makes sense to access the variables directly (imagine generating getters and setters for every little class you have). You could of course use a struct in this case aswell.
With larger classes it common practice to use the getters and setters to ensure that other classes don''t have access to something you don''t want them too.
If you return a constant reference from your accessor, there should be no performance issue, as you are not creating any temproary variables. One reason to use accessors is to make sure a value passed in is withing range. Again, you can use constant references in your parameter of your setter which will ensure it is the correct type and wont cause any performance loss.
well, its a fact that each time you have to call a function, it takes a little time. so retreiving a var using a get-function is in fact a little slower than getting it right away.
but theres another factor: making them private or protected helps preventing bugs/errors. This way your program cant access data it shouldnt be allowed to access.
It is a very little bit slower. Its not noticable on computers today. I mean if it really mattered you could do register int a; that will put a''s contents into the CPU not the memory, it is the compilers decision though.
quote:Original post by Ruudje well, its a fact that each time you have to call a function, it takes a little time. so retreiving a var using a get-function is in fact a little slower than getting it right away.
Most getter/setter functions can be inlined, and thus have no overhead.
Ok, thanks all of you. I'll get my simple classes as per-var access and my complex ones with setter and getters, I think it will be the best way. (I mean I see no benefit in constructing a Set/Get for my 3DVector class for example, 'cause I call it zillions times and it's very simple, but in any other case, I'll use Set/Get).
EDIT: I've already inlined all my intensive-used methods (it's worth!!) --------------------------------------- "It's only a bit, it can't hurt you..."
[edited by - -Egon- on July 11, 2003 12:58:07 PM]
--------------------------------------- "It's only a bit, it can't hurt you..."