Re: The use of const reference instear of getter
Turin wrote:
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 mor
effecient than using a getter?
You have got it completely backwards: Using such a member reference is
going to increase the size of the objects instantiated from the class
(which a member function won't do), it will make instantiating your
class slower (because the reference needs to be initialized) and
accessing the element will be slower (because the compiler will most
probably be unable to optimize the indirection away, as it has no way of
knowing at compile time where the reference is pointing to).
An inline member function will not increment the size of the class,
will have zero overhead at instantiation (and basically anything else),
and will have zero overhead to access the member variable (at least if
the compiler is optimizing).
If what you fear is that a member function will cause slow code,
inlining such a simple member function is one of the easiest
optimizations for any C++ compiler to do. (The only situation where it
will not inline it is when you have all optimizations turned off, eg.
for debugging purposes.)
From an object-oriented point of view your reference is also exposing
the internal implementation details of your class, which the getter
function isn't. (In other words, you could later change the
implementation of your getter function to something completely different
without breaking anything, but you won't be able to do that with your
reference solution.)