struct MyClass
{
operator const char* ()
{
return "hello";
}
};
int main()
{
MyClass obj;
std::cout << obj; // ok
printf("%s\n", obj); // Crash
}
Why does object with operator const char* can not be automatically converted to const char* string in printf for mapping the %s?
Is it just because there is no type awareness in printf-like functions and %s only expect a array of char with terminal 0?
Why? Because of the limitations on variadic parameters in C++: they have essentially no type, you can think of them as void * (but they're not).
So knowing that, the compiler has no idea you think that should be a string. It could very well need to be an integer, or a double, or another object. Or just itself, which the compiler chooses.
When you call printf with:
printf("%s\n", obj);
the compiler does not use the auto conversion function to convert obj to char const*. obj is passed to printf by value and printf tries to treat that value as though it is char const*. As a consequence, your program exhibits undefined behavior. You'll have to explicitly cast obj to char const* to make your program behave predictably.
printf("%s\n", (char const*)obj);
If you turn on warning levels in your compiler, you'll probably see something to indicate that using obj in that printf call is not right. With g++ -Wall, I get:
socc.cc:16:23: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘MyClass’ [-Wformat=]
printf("%s\n", obj); // Crash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With