I would like to know, which one is more optimal accessing a member variable of a class through object pointer( as i am accessing it through friend function concept) or by using getter and setter method of a class.
2 Answers
To me, the best is an inline getter.
inline int GetValue() const {return Value;}
By the way, you can take a look at this answer

- 1
- 1

- 29,063
- 15
- 95
- 142
Typically, you'd write getters and setters inline, so there should be no overhead. Even with a separate definition, a good compiler should inline these calls through whole program optimization.
If this is not the case though, profile and see if performance is actually affected before you take any decision.
Note though that accessing members from outside (directly, from a friend
or even getters and setters) breaks encapsulation. The friend
option limits this to a specific class, so WRT this it's slightly better. If you must access those members, go with friend
. If you have tons of friends, better go with getters/setters (at least you have a single access point, right). If performance is an issue (measurable), go with public members.

- 253,575
- 64
- 457
- 625
-
Hi Can give me some link for profiling, I am new into optimization part, I would be greatful if you could share :) – add2c Jan 07 '14 at 10:23
-
@add2c depends on the platform you're using. Just google for "profiling C++ applications on
" – Luchian Grigore Jan 07 '14 at 10:24 -
I have only one friend of that class actually this classe has some other member that belong to different class , so i thought to make use of friend and indirectly accessin this next level of class member( belong to some third class) – add2c Jan 07 '14 at 10:27