New to C++ My understanding is endl will add a new line. So with the following piece of code:
#include <iostream>
using namespace std;
void printf(string message);
int main()
{
cout << "Hello" << endl;
cout << "World" << endl;
printf("Hello");
printf("World");
return 0;
}
void printf(string message) {
cout << message << endl;
}
I expect the output to be:
Hello
World
Hello
World
But, strangely, the output is:
Hello
World
HelloWorld
Looks like, when called from the user-defined method, endl is not adding new line..?? What is wrong with my understanding here. Please advise.
The problem is that due to overload resolution the built in
printffunction is selected over your custom definedprintffunction. This is because the string literal"Hello"and"World"decays toconst char*due to type decay and the built inprintffunction is a better match than your custom definedprintf.To solve this, replace the
printfcalls with :In the above statements, we're explicitly using
std::string's constructor to createstd::stringobjects from the string literal"Hello"and"World"and then passing thosestd::stringobjects by value to yourprintffunction.Another alternative is to put your custom
printfinside a custom namespace. Or you can name your function other thanprintfitself.