#include <iostream>
#include <string>
usingnamespace std;
class User {
string name;
int age;
public:
User( string str, int yy ) { name = str; age = yy; }
friend ostream& operator<<(ostream& os, const User& user) { //(C)
os << "Name: " << user.name << " Age: " << user.age << endl;
}
};
int main()
{
User us( "Zaphod", 119 );
cout << us << endl; // Name: Zaphod Age: 119 //(D)
return 0;
}
The operator << is overloaded but the return os; statement is missing. I thought this was an error but g++ compile this source and I can run it without errors in linux. How can cout << us return a reference to cout if the overloaded operator does not have the return statement?
I think that the GCC allows that kind of thing... (returning the value of the last expression) but line eleven should read 11return os << "Name: " << user.name << " Age: " << user.age << endl;
You can force the error by asking g++ to be strictly conformant to a specific standard.
g++ -Wall -pedantic -std=c++98 ...
or, IIRC,
g++ -Wall -pedantic -ansi ...
for the current standard (which is currently C++98).
Thanks for your answer, the options you suggest for g++ gives only warnings not errors. It seems that the standard allows that the return statement is missing from a function but the resulting behavior is undefined.
I guessed too that gcc returns the the value of last expression but if you try the following code you don't get the sum result: