Search code examples
c++streamostream

Ostream output gives extra adress, when using nested functions


I have few functions with switches dealing with ostreams to specify exact template type for object to print. BUT somehow when i'm using nested functions extra address appears in output stream.

Code example:

#include <iostream>

using namespace std;


ostream & tmp2( ostream & in )
{
   return in << "out";
}

ostream & tmp( ostream & in )
{
   return in << tmp2( in );
}

int main(int argc, char** argv)
{
   int t = 2;
   switch (t)
   {
      case 2:
         std::cout << tmp;
   }
   return 0;
}

OUTPUT: "out0x600e08"

any ideas why is that and how to prevent this?


Solution

  • ostream & tmp( ostream & in )
    {
       return in << tmp2( in );
    }
    

    That is equivalent to:

    ostream & tmp( ostream & in )
    {
       tmp2(in);
       in << in;   // This line causes the extra output.
       return in;
    }
    

    You probably meant to use:

    ostream & tmp( ostream & in )
    {
       return tmp2( in );
    }