Computer Science Canada

[C++] Why no one should ever write "void print()"

Author:  wtd [ Tue Mar 16, 2004 9:50 pm ]
Post subject:  [C++] Why no one should ever write "void print()"

C++ offers a powerful capability to programmers in the form of operators that can be overloaded, as evidenced by code like:

code:
std::cout << "hello world" << std::endl;


Where the operator overloading looks like:

code:
std::ostream& operator<<(std::ostream&, const std::string&);


This means we can write similar code to let any type of data fit on the other side of that << operator. The advantage of this approach is flexibility. If you're just using a print() function which sends the data to std::cout, then you'd have to create a new function to output to a different destination.

By overloading the operator you can output to any output stream, including files, since std::ofstream is a child of std::ostream.

Any questions? Smile


: