Implicit conversion : const reference vs non-const reference vs non-reference
Posted
by
Nawaz
on Stack Overflow
See other posts from Stack Overflow
or by Nawaz
Published on 2011-01-16T08:09:16Z
Indexed on
2011/01/16
8:53 UTC
Read the original article
Hit count: 576
Consider this code,
struct A {};
struct B { B(const A&) {} };
void f(B)
{
cout << "f()"<<endl;
}
void g(A &a)
{
cout << "g()" <<endl;
f(a); //a is implicitly converted into B.
}
int main()
{
A a;
g(a);
}
This compiles fine, runs fine. But if I change f(B)
to f(B&)
, it doesn't compile. If I write f(const B&)
, it again compiles fine, runs fine. Why is the reason and rationale?
Summary:
void f(B); //okay
void f(B&); //error
void f(const B&); //okay
I would like to hear reasons, rationale and reference(s) from the language specification, for each of these cases. Of course, the function signatures themselves are not incorrect. Rather A
implicitly converts into B
and const B&
, but not into B&
, and that causes the compilation error.
© Stack Overflow or respective owner