Unlike printf()
function it do not have format specifier from where compiler guesses the no. of arguments. Then what happens in case of cout?
How object cout prints multiple arguments?
33.9k views Asked by sony AtThere are 4 answers
<<
and >>
operator are overloaded for different data types. No need of format specifier in this case. For <<
operator following definitions are in ostream
class:
ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (void* val);
ostream& operator<< (streambuf* sb );
ostream& operator<< (ostream& (*pf)(ostream&));
ostream& operator<< (ios& (*pf)(ios&));
ostream& operator<< (ios_base& (*pf)(ios_base&));
C++ streams have no implementation for inputting/outputting multiple values. They have the formatted input/output operators >>/<<, which separate each output value. Besides these, they have unformatted functions operating on a single value (array)
Example: A single ostream& operator << (T a);
puts a value 'a' into the stream and returns a reference to the stream, itself. That reference to the stream is eligible to accept a next value 'b' as in stream << a << b;
Note: This compiles for defined operators IStream& operator >> (IStream&, Type)
and OStream& operator << (OStream&, Type)
, only. A defined operator may be an operator provided by the standard library or a user defined operator.
IOStreams only take one argument at a time, so it works just fine. :)
The magic of operator overloading means that this:
is actually this:
or this:
(Depending on the types of
a
,b
andc
, either a free function or a member function will be invoked.)and each individual call is to an overload that accepts the type you give it. No argument-counting or format strings required, as they are with your single calls to
printf
.