26

Apologies for this, I am a student trying to learn C++ and I just thought it'd be better to ask than to not know.

I understand what the "address of" operator & and the const keyword mean separately. But when I was reading some sample code I saw const&, and I just wanted to know what it means.

It was used in place of an argument in a function prototype, for example:

void function (type_Name const&);

If only one of them were used I would understand but I am a little confused here, so some professional insight would be great.

q-l-p
  • 4,304
  • 3
  • 16
  • 36
Fela Pano
  • 261
  • 1
  • 3
  • 3
  • 2
    I'm sure someone will shortly provide a thorough answer, but here's a hint: that's not an address-of operator. – Carey Gregory Oct 16 '13 at 23:25
  • 3
    Please see one of the fine introductory books on the book list: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Mark B Oct 16 '13 at 23:25
  • 1
    Well, I assume you're either learning from a teacher or from a book, both should have the answer. – GManNickG Oct 16 '13 at 23:26

2 Answers2

36

Types in C++ are read right to left. This is, inconveniently just the opposite direction we like to read the individual words. However, when trying to decide what qualifiers like const or volatile apply to, putting the qualify always to the right make it easier to read types. For example:

  • int* const is a const pointer to a [non-const] int
  • int const* is a [non-const] pointer to a const int
  • int const* const is a const pointer to a const int

For whatever unfortunate accident in history, however, it was found reasonable to also allow the top-level const to be written on the left, i.e., const int and int const are absolutely equivalent. Of course, despite the obvious correct placement of const on the right of a type, making it easy to read the type as well as having a consistent placement, many people feel that the top-level const should be written on the left.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
21

In this context, & is not an address-of operator.

void function (type_Name const&);

is equivalent to:

void function (const type_Name &);

which is nothing but prototype of function taking argument by const reference. You should study this kind of topics on your own, ideally from some good book. However, if you're looking for some additional material, these questions might help you too:
What are the differences between a pointer variable and a reference variable in C++?
Pointer vs. Reference, When to use references vs. pointers, Pass by Reference / Value in C++

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167