-4
#include <iostream>

using namespace std;

ostream& point(ostream& s)  //Point a manipulator func
{       
    s << "-->";
    return s;

}

int main()    
{    
    cout << point << 10;
    return 0;
}

//-------------------------------------------------------------------------//

Udesh
  • 11
  • 4

2 Answers2

1

Badly.

That function has several bugs.

  1. It streams directly to cout, regardless of what s is. So if you streamed point to another stream, not cout, the result would go to the wrong place.

  2. It is missing a return statement, so your program has undefined behaviour. Your compiler should have warned you about that. You're supposed to return the stream again to permit chaining. This is a convention expected by the IOStream.

It could be correctly written like this:

ostream& point(ostream& s)
{
   s << "-->";
   return s;
}

This version "works" because IOStreams are specifically designed to accept a "pointer-to-function" of this form and to execute it with a reference to the stream as its first argument. It's a feature. It's how the IO manipulators (including endl!) do their job.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

The output stream class has some overloads taking certain function pointers as parameters. In particular there is an output operator declared as (ignorung that there are actually templates involved):

std::ostream& std::ostream::operator<< (
     std::ostream& (*manip)(std::ostream&));

When this operator is called it calls the passed function with itself, i.e., something like this:

manip(*this);

That is, “inserting” such a manipulator function causes the function to be called with the stream as argument..

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • I dont understand what does this means "(*manip)(std::ostream&)" ? – Udesh Dec 01 '18 at 20:37
  • @Udesh: this is part if the type of a pointer to a function (it is missing the return type): in general it looks like `R(*name)(A...)`. `R` is the return type (in this case `std::ostream&`), `name` is simply the name and the `*` in front of it is indicating that it is a pointer. `A...` is the list of parameter types, in this case just `std::ostream&`. You get a function pointer by taking a functions address using `&f` or by decay to a pointer when a function is named in a context where a function pointer is expected (this is what is normally used for manipulators). – Dietmar Kühl Dec 01 '18 at 20:49