I am learning C++. One of the things I have trouble to understand, is when to put &
, const
or const &
after the declaration of a member function.
An example:
class Foo
{
// When to use which one?
bool bar(int baz);
bool bar(int baz) const;
bool bar(int baz) &;
bool bar(int baz) const &;
}
My intuition says:
- Use
const
orconst &
whenver possible, as it states that the function does not alter the object, and therefore can still be used when having aconst myfoo
somewhere. - Passing
&
orconst &
will not copy the object the member function is called on, while a function without the&
behind it would. - Therefore, always use
const &
unless you cannot?
Are these statements true?
I was unable to find information about this thus far, quite possibly because I do not know the proper jargon term for 'these things behind functions that alter the functions behaviour'.
When to use which version?