6

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 or const & whenver possible, as it states that the function does not alter the object, and therefore can still be used when having a const myfoo somewhere.
  • Passing & or const & 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?

Qqwy
  • 5,214
  • 5
  • 42
  • 83
  • 1
    _"Passing & or const & will not copy the object the member function is called on, while a function without the & behind it would."_ No. Instead of guessing, consider reading the documentation. You do not need to know what the search term is; you only need to open your C++ book and start reading. – Lightness Races in Orbit Oct 09 '16 at 10:16
  • const says argument should not be modified and is enforced by compiler at compile time checking. – hg_git Oct 09 '16 at 10:46
  • @LightnessRacesinOrbit I would not ask this question if my C++ book provided an answer. It seems that my C++ book, the C++ Annotations v10.5.1, is lacking this information. – Qqwy Oct 09 '16 at 10:53
  • @Qqwy: No; read through to §7.7 for what `const` member functions mean. For the trailing `&`, your book is too out-of-date, but you can refer to [this question](http://stackoverflow.com/q/21861148/560648) or [a better book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) that actually teaches the language in entirety. – Lightness Races in Orbit Oct 09 '16 at 10:55
  • 1
    @hg_git: No, that is not what it means. – Lightness Races in Orbit Oct 09 '16 at 10:58
  • @LightnessRacesinOrbit yeah sorry that means when const is present with the argument. was sleepy atm and wrote this thing. This const refers to *this becoming const and not being able to modify members through this method. – hg_git Oct 11 '16 at 17:39

0 Answers0