I have this function :
void
SpookyBoy( bool Troublemaker, const Glib::ustring& name, HorrorPunkBand& band );
if I remove the word const
I got this error :
no known conversion for argument 2 from ‘const char [5]’ to ‘Glib::ustring&’
I just wonder what does the compiler, can someone explains to me why with the word const
the compiler can cast ?
even if I have to admit the two questions are similar for someone who already knows the answer (at fortiori), but certainly not for someone who does not know yet the answwer (at priori).
You are apparently calling your function with a string literal as an argument
SpookyBoy(..., "1234", ...);
The compiler can implicitly convert the string literal (which in this case has type const char [5]
) to type Glib::ustring
. But the result of that implicit conversion is a temporary object. In C++ language only const lvalue references can be bound to temporary objects. Non-const references cannot be bound to temporary objects.
Without that const
in function declaration you'd have to call your function as
Glib::ustring name("1234");
SpookyBoy(..., name, ...);
i.e. by explicitly introducing a named object of Glib::ustring
type and passing it as an argument.
P.S. See also Why const for implicit conversion?