Operator "<<" overloading return type
c++, c++11
Solution
You can return `void` from stream extracting `operator >>`, just like you can return `void` from a stream inserting `operator <<`. And just like with the inserting one, it will prevent you from doing chaining:
cPoint p, q;
cin >> p >> q; // This would fail with return type void
... and the very common test-correctness idiom:
cPoint p;
if (cin >> p) {
}
Problem
Suppose there is a cPoint class. ``` class cPoint { int x, y, z; }; ``` I wanted to print all of three variables in a single statement. So, I overloaded operator << just like ``` friend std::ostream& operator<< (std::ostream &cout, cPoint &p); std::ostream& operator<< (std::ostream &out, cPoint &p) { out << p.get_x() << " " << p.get_y() << " " << p.get_z() << std::endl; return out; } ``` Make sense? My question lies in the lines of that what would happen in case of insertion operator(>>). I overloaded that as well to take the values of x, y and z into a single statement. ``` friend std::istream& operator>> (std::istream &cin, Point &p); std::istream& operator>> (std::istream &in, Point &p) { int tmp; in >> tmp; p.set_x(tmp); in >> tmp; p.set_y(tmp); in >> tmp; p.set_z(tmp); } ``` Clear? ``` int main() { cout << p << endl; cin >> p; } ``` I know that if operator<< returned void then the compiler evaluates cout << p << endl; Due to the precedence/associativity rules, it evaluates this expression as (cout << cPoint) << endl;. cout << cPoint calls our void-returning overloaded operator<< function, which returns void. Then the partially evaluated expression becomes: void << endl;, which makes no sense! But what would happen in case of >>. Why can't I return a void for >> as like: ``` void operator>> (std::istream &cin, Point &p); ``` Because it does not matter if cin >> p returns void or something else. There is no other operand who could use it. This is not clear.