Re: The use of const reference instear of getter
On Aug 4, 3:52 pm, Jerry Coffin <jcof...@taeus.com> wrote:
In article <7210b453-7a0e-4af3-a159-98f7848d28dd@
34g2000hsh.googlegroups.com>, omar.ham...@gmail.com says...
[ ... ]
However, if all I am interested in when making a member
private is to disallow the modification of the value of that
member (read-only member), then how about doing the
following:
class A {
public :
const int& ref_to_priv_member;
A() : ref_to_priv_member(priv_member) {
/* Blah */
}
private :
int private_member;
};
I would like to know the opinion of C++ experts on this and
if there are any side-effects of this. Also from the
perferformance point of view, isn't using this more effecient
than using a getter?
Looking forwards to hearing your opinions.
This works perfectly well, and doesn't really have any
side-effects.
With most compilers, it will increase the size of the object.
(And since the original poster mentionned performance, I expect
that with most compilers, compared to a getter, it will generate
slower code. Internally, the reference will be implemented as a
pointer, and that ain't good for optimization.)
The other problem is consistency. When you need to return
something that isn't really a member variable, you use a
function call; for the member variable, you use a reference.
Isn't that exposing internal details which the client code
should not be concerned with?
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34