Overloading the stream insertion (<<) operator? - c++

When we overload the stream insertion operator to work on user defined objects, we usually define it as a global friend function as follows:
ostream& operator << (ostream& out, const MyClass& x) {
// Do something
return out;
}
My question is, I believe the object cout (which is a global object) is passed as the first argument to this function. But, why? It's a global function, so it is accessible in this function anyway, why pass it as an argument. In other words, why not do the following:
ostream& operator << (const MyClass& x) {
// Do something
return cout;
}

There are two reasons.
One is semantic: the first argument need not be std::cout. It can be any std::ostream, be it std::cerr, a std::ofstream, a std::ostringstream, etc.
The second is syntactic: << necessarily takes two arguments, and there's no way to write an overload without two arguments (though the first argument can be a this argument).

Related

Calling a function which manipulates the ostream doesn't require parentheses. C++

I know a function cannot be called without a parentheses, however, let's say I have this piece of source code:
#include<iostream>
using namespace std;
ostream& test(ostream& os){
os.setf(ios_base::floatfield);
return os;
}
int main(){
cout<<endl<<scientific<<111.123456789;
cout<<endl<<test<<111.123456789;
}
/// Output:
/// 1.11235e+002
/// 111.123
There isn't any overloading for the left-shift operator, yet when I call the test(ostream& os) function in the cout at the main function, it does not require any parentheses. My question is why?
There isn't any overloading for the left-shift operator
Yes there is, it's defined in <ostream>.
It uses exactly the same technique that allows endl and scientific to work. There is an overload taking a function pointer, which calls the function pointer when it's written to a stream.
basic_ostream has these member functions which accept function pointers:
// 27.7.3.6 Formatted output:
basic_ostream<charT,traits>&
operator<<(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))
{ return pf(*this); }
basic_ostream<charT,traits>&
operator<<(basic_ios<charT,traits>& (*pf)(basic_ios<charT,traits>&))
{ return pf(*this); }
basic_ostream<charT,traits>&
operator<<(ios_base& (*pf)(ios_base&))
{ return pf(*this); }
cout << test uses the first of those overloads, which is equivalent to cout.operator<<(&test), which does return test(*this); so the call happens inside the overloaded operator<<.
ostream has overload of operator << for this case:
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
Calls func(*this);. These overloads are used to implement output I/O
manipulators such as std::endl.

Understanding streams: how does this function work?

Consider the following function:
template <class T>
void to_string(const T& val, string& s) {
ostringstream o;
o << val;
s = o.str();
}
I'm not sure how this function works. I have two assumptions, please tell me which one is correct (if any):
ostringstream has an overload of operator<< that takes whatever T is (unlikely).
There's a global function with the signature ostream& operator<<(ostream& stream, Sometype& t). This allows a T to be written to the ostringstream, assuming it's a Sometype.
Which one of these is more likely correct? I'm assuming the second one, but I'm not sure.
For some types (most arithmetic ones) there is a member function operator<< in ostream.
For all other types operator<< must be a non-member function with the exact signature that you proposed in your second bullet. Although the second parameter is SomeType const& in most (if not all) cases.

Why does operator>> (or <<) overloading function need to receive an i\ostream reference?

From cplusplus.com, I saw that ostream class's member function operator<< looks like this:
ostream& operator<< (bool val); ostream& operator<< (int val);
.... and so on.
It does make sense because when you use the Cout object like cout<<x you activate the ostream& operator<< (int val) function, so you actually use the << operator on Cout object. This is very much like every other operator and sends the int variable to the function. What is the difference and what exactly happens when I want to stream an object of my own? Why does the syntax is suddenly ostream& operator<< (**ostream &os**, object ob)?
Why do I need to add the ostream var? I am still using cout<<ob so whay isnt it just ostream& operator<< (object obj)? All I pass is my object. The cout object is allready there.
operator<< is generally defined as a free function; that is, not a member function. Since it is an overloaded binary operator, that means it get's its left argument first and its right argument second.
The operator<< traditionally returns a reference to its left argument to enable the idiomatic chain of output.
To make it obvious to the reader, I tend to define my operator overloads using the lhs and rhs abbreviations; an operator<< would look similar to this, for some type T.
std::ostream& operator<<(std::ostream& lhs, T const& rhs)
{
// TODO: Do something
return lhs;
}
As a member function
As with other binary it could be defined as a member function. That is, let us suppose that you with defining your own iostream. Amongst other things, your class declaration may look like this. Again, T is a particular type.
class MyIOStream : public iostream
{
public:
MyIOStream& operator<<(T const& rhs);
}
In this case operator<< is a member function. It has the same semantics when used as <<.
References
Operators in C and C++ - a great summary of all the operators you can overload and their typical arguments.
why do I need to add the ostream var?
I'm sure it's there so that you can chain outputs together:
cout << foo << bar
The first call, cout << foo will result in an ostream reference that can be used for the << bar part.
Some of the stream extractors are members of basic_istream; because they are members, the basic_istream argument is implied. Some of the stream extractors are not members of basic_istream. Because they are not members, the basic_istream argument has to be part of the declaration.
Like this (oversimplified):
class basic_istream {
public:
basic_istream& operator>>(int& i);
}
basic_istream& operator>>(basic_istream&, std::string& str);
Both can be called in the same way:
int i;
std::cin >> i; // calls basic_istream::operator>>(int&)
std::string str;
std::cin >> str; // calls operator>>(basic_istrea&, std::string&)

"recursive on all control paths, function will cause runtime stack overflow" on overloaded << operator

I have a section of code that seems to have a recursive warning when I compile, any ideas why?
ostream& operator << (ostream& out, const node& rhs)
{
out << rhs.get_data();
return out;
}
It is calling this function:
node::value_type node::get_data() const
{
return data;
}
This is just a guess, since you haven't posted a self-contained example. In particular, the definition of node would be very useful.
I think that, for some reason, the compiler is choosing to convert rhs.get_data() into a node, probably using an implicit conversion constructor, rather than selecting an overload of operator<< that takes node::value_type. You should:
Make sure that operator << (ostream&, node::value_type) has been declared before your definition of operator<<
If node has a constructor that takes value_type, then it's probably best to make it explicit to avoid unexpected implicit conversions.

C++ overloading

The following code is giving me a compilation error. Can anyone please tell me why?
class mytype {
public:
int value;
mytype(int a) {
value = a;
}
friend ostream& operator<<(ostream& stream, const mytype& a) {
stream << a.value;//works
return stream;
}
friend ostringstream& operator<<(ostringstream& stream, const mytype& a) {
stream << (a.value);//compilation error
return stream;
}
};
Error:
error C2027: use of undefined type
'std::basic_ostringstream<_Elem,_Traits,_Alloc>'
Upon fixing that:
error C2666: 'operator <<' : 18 overloads have similar conversions
Final fix:
Declare constructor as explicit. Works on MSVC then.
I wonder why.
error C2027: use of undefined type 'std::basic_ostringstream<_Elem,_Traits,_Alloc>'
You need #include <sstream> to get the [i/o]stringstream classes.
About the other errors
The problem with an overload of the form
ostringstream& operator<<(ostringstream& stream, const mytype& a)
is that it matches an ostringstream exactly. Why is it a bad thing to have a more exact overload? From the standard, §13.3.3/1-2:
a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2) …
If there is exactly one viable function that is a better function than all other viable functions, then it is the
one selected by overload resolution; otherwise the call is ill-formed
Therefore if operator<<( ostream &, int ) and operator<<( ostringstream &, mytype const & ) are both candidates for stream << value, the former matches int exactly with no conversion but the latter matches ostringstream exactly. Therefore neither can be "not worse" for all arguments, and neither candidate may be chosen.
But the code is valid because of a loophole. Your overload is not a candidate at all, except when you actually use your type in the function call. When you declare/define a friend inside a class block, it does not introduce it to any namespace scope; it merely associates it with the class scope, which allows it to be found if that class type describes one of the arguments being passed.
The standard has this to say about friend declarations, although it's in another section (14.6.5):
Friend declarations do not introduce new names into any scope…
So, MSVC tried to be nice and proactively introduced your friend to its enclosing namespace. Strike against MSVC.
However, when I attempted to add a declaration equivalent to what MSVC did "for free," Comeau and GCC nicely resolved the resulting overloading conflict — strike against them. Or is it? As it turns out, the overloaded call occurs earlier in the file than my recommended declaration. If I move the declaration before class mytype { (which requires forward-declaring mytype), then both properly complain about the ambiguity.
Using an overload before it is declared in namespace scope appears to be well and good according to §3.3-3.4 of the Standard. So actually GCC and Comeau were both in the right. The point of declaration is right after the name of the declared object. (And last I checked, self-referential function declarations can still crash GCC.) ADL invokes unqualified lookup into the enclosing namespace at a point immediately before the enclosing class. (3.4.1/8 final bullet, 3.4.1/9, 3.4.2/2a.) If the friend hasn't been declared before the class, it's legitimately not a candidate. (7.3.1.2/3) Isn't C++ a beautiful language?
How keep the simplified example on GCC, but break subsequent code.
friend ostringstream& operator<<(ostringstream& stream, const mytype& a) {
stream << (a.value);//compilation error
return stream;
}
};
ostringstream& operator<<(ostringstream& stream, const mytype& a); // <- here
Following this declaration, it will be impossible to write an int into an ostringstream.
How to break everything uniformly, with simpler declaration semantics.
class mytype; // <- here
// and here:
inline ostringstream& operator<<(ostringstream& stream, const mytype& a);
class mytype {
public:
Following this declaration, it will be impossible to write an int into an ostringstream… including the friend declarations inside class mytype {}.
Actual solution.
The stream classes are supposed to be indistinguishable. If you really want to determine whether a given stream feeds a string in memory (and you shouldn't), it's best to look at its internal streambuf object, returned by rdbuf(), which actually performs the I/O gruntwork. Even a generic ostream object can have ostringstream functionality if given a stringbuf.
if ( typeid( stream.rdbuf() ) == typeid( stringbuf * ) ) {
// this is effectively a stringstream
} else {
// not a stringstream
}
There is an overload ambiguity in the call to operator<< in the ostringstream overload.
stream << a.value;
There are a number of operator<< overloads that are members of the ostream class, which is a base class of ostringstream. One of these is declared as:
ostream& ostream::operator<<(int);
This overload is an exact match for the right-hand side (a.value is an int) but requires a derived-to-base conversion on the left-hand side (stream is an ostringstream, which is derived from ostream).
However, there is also your ostringstream overload:
ostringstream& operator<<(ostringstream&, const mytype&);
This overload is an exact match for the left-hand side (stream is an ostringstream), and a user-defined converting constructor (your mytype(int) constructor) can be used to convert a.value (an int) to a mytype.
Since one overload matches the first argument better and the other overload matches the second argument better, there is an ambiguity. You can fix this either by:
Explicitly converting the left-hand side to an ostream (using (ostream&)stream = a.value;), or
Remove the user-defined conversion by making the constructor explicit.