Fela Pano
Fela Pano

Reputation: 261

What does 'const&' mean in C++?

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.

Upvotes: 26

Views: 38492

Answers (2)

Dietmar Kühl
Dietmar Kühl

Reputation: 153820

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.

Upvotes: 38

LihO
LihO

Reputation: 42083

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++

Upvotes: 23

Related Questions