Search code examples
c++operator-overloadingostream

ostream& operator<< (ostream& (*pf)(ostream&));


my problem is to understand the (ostream& (*pf)(ostream&))

  1. why reference to pointer pf? In my understanding necesseary for allocation
  2. why the second (ostream&)?

I found it while reading about operator overloading.

Thanks Uwe


Solution

  • why reference to pointer pf? In my understanding necesseary for allocation

    That is an incorrect understanding. pf is a pointer to a function. Its return type is std::ostream& and the only argument is also a std::ostream&.

    why the second (ostream&)?

    The function gets called using an ostream object, which gets passed by reference. The function returns a reference to the same object.

    Let's take a look at the call.

    std::cout << std::endl;
    

    It is translated as:

    std::cout.operator<<(std::endl);
    

    std::ostream::operator<<(std::ostream& (*pf)(std::ostream&) can be implemented simply as:

    std::ostream& std::ostream::operator<<(std::ostream& (*pf)(std::ostream& str)
    {
       return pf(str);
    }