I know a function cannot be called without a parentheses, however, let's say I have this piece of source code:
#include<iostream>
using namespace std;
ostream& test(ostream& os){
os.setf(ios_base::floatfield);
return os;
}
int main(){
cout<<endl<<scientific<<111.123456789;
cout<<endl<<test<<111.123456789;
}
/// Output:
/// 1.11235e+002
/// 111.123
There isn't any overloading for the left-shift operator, yet when I call the test(ostream& os) function in the cout at the main function, it does not require any parentheses. My question is why?
Yes there is, it's defined in
<ostream>.It uses exactly the same technique that allows
endlandscientificto work. There is an overload taking a function pointer, which calls the function pointer when it's written to a stream.basic_ostreamhas these member functions which accept function pointers:cout << testuses the first of those overloads, which is equivalent tocout.operator<<(&test), which doesreturn test(*this);so the call happens inside the overloadedoperator<<.