Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the streams in C++?

Tags:

c++

stream

As you all know there are libraries using streams such as iostream and fstream.

My question is:

  • Why streams? Why didn't they stick with functions similar to print, fgets and so on (for example)?

They require their own operators << and >> but all they do could be implemented in simple functions like above, also the function

printf("Hello World!");

is a lot more readable and logical to me than

cout << "Hello World";

I also think that all of those string abstractions in C++ all compile down to (less efficient) standard function calls in binary.

like image 787
oh boy Avatar asked Apr 30 '10 16:04

oh boy


2 Answers

Streams have better type safety.

For instance printf("%s", a); can go horribly wrong if a is an integer. cout << a; doesn't have this problem.

Another issue is that streams better conform to Object Oriented design methodologies.

For instance you have a simple application that writes some output and then you want the output to go to a file instead of to the console. With C calls you'll have to replace all of the calls to printf to calls to fprintf and take care to maintain the FILE* along the way. With streams you just change the concrete class of the stream you're using and that's it, most of the code remains the same like so:

void doSomething(ostream& output)
{
   output << "this and that" << a;
}

doSomething(cout);
doSomething(ofstream("c:\file.txt"));
like image 114
shoosh Avatar answered Oct 02 '22 15:10

shoosh


For one, it allows you to take advantage of the C++ object model to create functions that do not care whether they are writing to standard output, a file, or a network socket (if you have a network socket that derives from ostream). E.g.

void outputFoo(std::ostream& os)
{
  os << "Foo!";
}

int main()
{
  outputFoo(std::cout);

  std::ofstream outputFile("foo.txt");
  outputFoo(outputFile);

  MyNetworkStream outputSocket;
  outputFoo(outputSocket);
}

And similarly for input streams.

Streams also have an advantage when it comes to inputting and outputting objects. What would happen if you wanted to read in an object with scanf?

MyObject obj;
scanf("??", &obj); // What specifier to use? 

Even if there were an appropriate specifier, how would scanf know how to fill in the members of the object? With C++ streams, you can overload operator<< and write

MyObject obj;
std::cin >> obj;

And it will work. Similarly for std::cout << obj, so you can write the object serialization code in one place and not have to worry about it anywhere else.

like image 24
Tyler McHenry Avatar answered Oct 02 '22 16:10

Tyler McHenry