Calling a function which manipulates the ostream doesn't require parentheses. C++

194 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

There isn't any overloading for the left-shift operator

Yes there is, it's defined in <ostream>.

It uses exactly the same technique that allows endl and scientific to work. There is an overload taking a function pointer, which calls the function pointer when it's written to a stream.

basic_ostream has these member functions which accept function pointers:

// 27.7.3.6 Formatted output:
basic_ostream<charT,traits>&
operator<<(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))
{ return pf(*this); }

basic_ostream<charT,traits>&
operator<<(basic_ios<charT,traits>& (*pf)(basic_ios<charT,traits>&))
{ return pf(*this); }

basic_ostream<charT,traits>&
operator<<(ios_base& (*pf)(ios_base&))
{ return pf(*this); }

cout << test uses the first of those overloads, which is equivalent to cout.operator<<(&test), which does return test(*this); so the call happens inside the overloaded operator<<.

0
On

ostream has overload of operator << for this case:

basic_ostream& operator<<(
    std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );

Calls func(*this);. These overloads are used to implement output I/O manipulators such as std::endl.