function overloading with and without passing by reference

S

SuperBald

Hello, I tried two functions as blow. The program is compiled successfully in g++ 4.4.1. I expect there will be a compilation error. Any hints? Thanks.

----------------------
#include <iostream>
using namespace std;

void f(int i)
{
cout << "No ref" << endl;
int k = i;
}

void f(int & i)
{
cout << "With ref" << endl;
int k = i;
}

int main()
{
f(1);
return 0;
}
 
Ö

Öö Tiib

Hello, I tried two functions as blow. The program is compiled successfully
in g++ 4.4.1. I expect there will be a compilation error. Any hints?
Thanks.

----------------------
#include <iostream>
using namespace std;

void f(int i)

{
cout << "No ref" << endl;
int k = i;
}

void f(int & i)
{
cout << "With ref" << endl;
int k = i;
}

int main()
{
f(1);
return 0;
}

Seems fine. What error did you expect? Example hint:

----------------------
#include <iostream>

void f(int&)
{
std::cout << "With ref" << std::endl;
}

int main()
{
f(1); // <- now you should have error here
}
 
S

SuperBald

int main()

{

f(1); // <- now you should have error here

}

I understand this. I know what I was confused now.

int main()
{
int i = 1;
f(i); //<< an error now

}


Thanks!
 
I

Ian Collins

SuperBald said:
Hello, I tried two functions as blow. The program is compiled
successfully in g++ 4.4.1. I expect there will be a compilation
error. Any hints? Thanks.

----------------------
#include <iostream>
using namespace std;

void f(int i)
{
cout << "No ref" << endl;
int k = i;
}

void f(int & i)
{
cout << "With ref" << endl;
int k = i;
}

int main()
{
f(1);
return 0;
}

{please clean up the mess google will inevitably make of your replies!}

There isn't any ambiguity in your code, assuming that's the error you
were expecting. 1 can't be bound to a non-const reference. If you were
to try and pass a variable or change the parameter to "int const&", the
call would be ambiguous.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top