How object cout prints multiple arguments?

33.9k views Asked by At

Unlike printf() function it do not have format specifier from where compiler guesses the no. of arguments. Then what happens in case of cout?

4

There are 4 answers

1
Lightness Races in Orbit On BEST ANSWER

IOStreams only take one argument at a time, so it works just fine. :)

The magic of operator overloading means that this:

std::cout << a << b << c;

is actually this:

std::operator<<(std::operator<<(std::operator<<(std::cout, a), b), c);

or this:

std::cout.operator<<(a).operator<<(b).operator<<(c);

(Depending on the types of a, b and c, 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.

2
haccks On

<< 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&));
3
Don Reba On

The compiler does not need to guess the number of arguments from printf's format specifier (though some do for better warnings). In case of cout, each << is a command to either output something or manipulate the stream, so there is no need for a format specifier.

0
AudioBubble On

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.