Reputation: 73
can someone please explain to me why a foo("Hello, I am an referncing string."); in a main() would call void foo(const string& s) and not the other defined foo() functions?
void foo(string& s)
{
cout << "(foo1): " << s << endl;
s = "Greetings from 'foo1'.";
}
//--------------------------------------------------------------------------
void foo(string* s)
{
cout << "(foo2): " << *s << endl;
*s = "Greetings from 'foo2'.";
}
//-------------------------------------------------------------------------
void foo(const string& s)
{
cout << "(foo3): " << s << endl;
}
Upvotes: 2
Views: 151
Reputation: 88017
Because it's the best overload. The type of "Hello, I am an referncing string."
is char*
(more or less) and std::string
has a constructor from const char*
. So the compiler creates a temporary std::string
and calls foo3. It doesn't call foo2 because there's no way to create a pointer to a std::string
and it doesn't call foo1 because of the rule that you cannot bind a non-const reference to a temporary.
Upvotes: 0
Reputation: 234875
A std::string
has a non-explicit constructor to a const char*
.
Your anonymous temporary string literal (which has a type const char[N]
where N
is the number of characters in the string, including the implicit NUL at the end) can decay to a const char*
when passed as a function argument.
And an anonymous temporary is allowed to bind to a const
reference.
Therefore with the three overloads you have, the one containing foo3
is viable and therefore selected at compilation time.
(The function containing foo1
is not viable since an anonymous temporary cannot bind to a non-const
reference - despite some earlier compilers allowing it in error. foo2
is far from being acceptable as that requires a pointer to a std::string
to be passed).
Do research the italicised terms here - there's quite a lot going on here.
Upvotes: 2