-1

Consider the following functions

int f (const int& i)
{
  cout << "in const reference function";
}
int f ( int &i)
{
  cout << "in non const reference function";
}
int main()
{
    int i;
    f(3);
    f(i);
}

In this case when the function call is bound with function definition, will it be at compile time or run time, as one is lvalue i and the other is not?

Other than this two functions are same in terms of number and type of parameters.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
OldSchool
  • 2,123
  • 4
  • 23
  • 45

3 Answers3

1

The overload will be chosen at compile-time. The "best-fit" will be chosen, which in this case depends on the cv-qualification of the function parameters:

From N4140 [over.ics.rank]/3

Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies:

  • Standard conversion sequence S1 is a better conversion sequence than S2 if

    • ...

    • S1 and S2 are reference bindings, and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.

int& is less cv-qualified than const int&, so will be chosen when possible. int& cannot bind to an rvalue like 3, so the const version is selected for that.

Demo

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

It is defined at compile time This code :

void f (const int& i)
{
    return;
}
void f ( int &i)
{
    return;
}
int main()
{
    int i = 12;
    f(3);
    f(i);
}

is compiled with gcc 5.2 to this :

movl    $3, -4(%rbp) //Declare variable i with 3
leaq    -4(%rbp), %rax
movq    %rax, %rdi
call    f(int const&)  //And call the method with const int&
leaq    -8(%rbp), %rax 
movq    %rax, %rdi
call    f(int&) //Call the method with only the reference
Pumkko
  • 1,523
  • 15
  • 19
0

This will be done at compile time only, because the type of parameters are different. Therefore these are not simple overloaded functions, calls of which can be determined at compile time only.

Nishant
  • 1,635
  • 1
  • 11
  • 24