Home > Net >  Why pass input/output stream in a function?
Why pass input/output stream in a function?

Time:05-17

Why would we want to do this:

#include <iostream>

void print(std::ostream& os) {
  os << "Hi";
}

int main() {
  print(std::cout);
  return 0;
}

instead of this:

#include <iostream>

void print() {
  std::cout << "Hi";
}

int main() {
  print();
  return 0;
}

Is there some certain advantage or functionality that is obtained only with the first version?

CodePudding user response:

Yes, the first version is significantly better. Like already mentioned in the comments, it allows you to use any kind of std::ostream, not just std::cout. Some of the most important consequences of this architectural choice are:

  1. You can use your function to print the required data to standard output, a file, a custom class written by your colleagues (e.g. database adapter, logger).

  2. It is possible to test your void print function. E.g.:

TEST(MyFunctionShould, printHello)
{
  std::string expectedResult("Hello");
  std::ostringstream oss;
  print(oss);
  ASSERT_EQ(expectedResult, oss.str());
}
  • Related