Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you define the ostream operator << for a class?

Tags:

c++

The question could be subjective, so the syntax of

std::ostream& operator << (std::ostream & o, const SomeClass &a) {
    return o << a.accessor().. ; 
}

When do you normally define this for the classes that you write, when do you avoid writing this friend function for your class.

like image 621
kal Avatar asked Oct 11 '25 18:10

kal


2 Answers

IF I want to stream a class I normally write this:

std::ostream& operator << (std::ostream& o, const SomeClass& a)
{
    a.print(o);
    return o; 
}

Then make print a const method on SomeClass that knows how to serialize the class to a stream.

like image 191
Martin York Avatar answered Oct 14 '25 09:10

Martin York


I would only overload operator<< when that has anything to do with streaming, or with shifting and the class is purely numeral. For writing something into an ostream, as in your code, i think it's fine. Anything else, i think, will cause confusion and i would better use member functions for those other purposes. One other application, which i think i would still do as an exception to the rule, is doing something like this:

StringList list;
list << "foo" << "bar" << "baz";

It is how Qt does it with its string list, and which i find quite nice.

like image 40
Johannes Schaub - litb Avatar answered Oct 14 '25 08:10

Johannes Schaub - litb



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!