0

Both >> and + operators are binary operators. What does the difference in their syntaxes mean?

Why does >> have a return type (return by reference)? I know it is stupid but I am really confused between their syntaxes and would love a brief explanation.

Sparse operator +(Sparse &s); //code for plus operator

friend istream & operator >>(istream &is,Sparse &s); //code for insertion operator
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
CHINMAY
  • 27
  • 2
  • 5
    Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Richard Critten May 13 '21 at 17:18
  • The first one is a member function, the second is a friend function, thus it has 2 arguments. – kebs May 13 '21 at 17:19

1 Answers1

1

operator+ combines the data of two input objects (in your example, the left-hand object is *this) and returns a new object containing the combined data.

operator>> (and operator<<) returns a reference to the stream that is being acted on. This allows for chaining multiple stream operations, eg:

cin >> var1 >> var2 ...;
// which is the same as:
// cin.operator>>(var1).operator>>(var2) ...
// or:
// operator>>(operator>>(cin, var1), var2) ...
// etc, depending on the particular types and operator overloads being used

cout << var1 << var2 ...;
// which is the same as:
// cout.operator<<(var1).operator<<(var2) ...
// or:
// operator<<(operator<<(cout, var1), var2) ...
// etc, depending on the particular types and operator overloads being used

Without being able to chain, stream operations would have to be called individually instead, eg:

cin >> var1;
cin >> var2;
...

cout << var1;
cout << var2;
...
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770