Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator<< overloading ostream

In order to use cout as such : std::cout << myObject, why do I have to pass an ostream object? I thought that was an implicit parameter.

ostream &operator<<(ostream &out, const myClass &o) {

    out << o.fname << " " << o.lname;
    return out;
}

Thanks

like image 321
Jess Avatar asked Dec 03 '10 16:12

Jess


People also ask

What is ostream operator in C++?

In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input. We must know the following things before we start overloading these operators. 2) These operators must be overloaded as a global function.

Can << operator be overloaded?

Fortunately, by overloading the << operator, you can! Overloading operator<< is similar to overloading operator+ (they are both binary operators), except that the parameter types are different.

Can << operator be overloaded in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.

Which operator is overloaded for CIN?

Notes: The relational operators ( == , != , > , < , >= , <= ), + , << , >> are overloaded as non-member functions, where the left operand could be a non- string object (such as C-string, cin , cout ); while = , [] , += are overloaded as member functions where the left operand must be a string object.


1 Answers

You aren't adding another member function to ostream, since that would require redefining the class. You can't add it to myClass, since the ostream goes first. The only thing you can do is add an overload to an independent function, which is what you're doing in the example.

like image 101
David Thornley Avatar answered Oct 04 '22 16:10

David Thornley