Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between << / >> operator overloading and Input/Output functions

Tags:

c++

I would really appreciate if someone could explain to me the difference between overloading the input/output operators, for example:

friend ostream& operator<<(ostream& ost, const myClass& obj) {
    return ost << obj.x << obj.y;
}

and Output/Input functions like these:

void Output(ostream& ost) {
    ost << x << y;
}

What are they used for, examples etc. Everything is acceptable. Thanks!

like image 973
hopittyhop Avatar asked Nov 29 '25 05:11

hopittyhop


1 Answers

Overloading the << operator will allow you to chain output operations:

myClass a, b;

...

cout << a << ' ' << b;

Using your alternate implementation, you would have to write:

myClass a, b;

...

a.Output(cout);
cout << ' ';
a.Output(b);

The first version makes it easier to quickly see how the output will be formatted. It is also the standard way to use streams in C++.

like image 77
Jørgen Fogh Avatar answered Dec 01 '25 19:12

Jørgen Fogh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!