-2

What's the difference betweeen void func(const int& i) and void func(int& i). If const is cut off at the top level, is it even possible to call the second overload? Why are const overloads preferred? The following will always select the first overload:

func(42);
func(int{42});
int i = 42;
func(i);
int &j = i;
func(j);
func(i + 1);

Whoops, I see what my problem is now. I had typed cout << "const\n" in both functions, so it looked like it always calling the first overload. Sorry guys.

stefan
  • 10,215
  • 4
  • 49
  • 90

2 Answers2

2

const is a hint to yourself and other developers, that you don't intend to modify the observed object. The const overload is selected if the argument is const:

#include <iostream>

void f(const int&)
{
    std::cout << "f(const int&)\n";
}

void f(int&)
{
    std::cout << "f(int&)\n";
}

int main()
{
    int a = 0;
    const int b = 0;
    int& c = a;
    const int& d = a;
    f(a);
    f(b);
    f(c);
    f(d);
}

This will output

f(int&)
f(const int&)
f(int&)
f(const int&)

See this demo.

As you can see, it is not always the const overload.

stefan
  • 10,215
  • 4
  • 49
  • 90
0

What's the difference betweeen void func(const int& i) and void func(int& i).

The difference bettween void func(const int& i) and void func(int& i) is that you cannot change i in the first function, while you can in the second.

is it even possible to call the second overload?

The second function will be selected if the argument is not const.

Why are const overloads preferred?

It depends. You cannot use const if you plan to change its value. And you should use const when you want to be sure not to change variable accidentally or intentionally. Check out this post: Use const wherever possible in C++? for more info.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174