Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How object cout prints multiple arguments?

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

like image 742
sony Avatar asked Dec 24 '22 18:12

sony


2 Answers

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.

like image 75
Lightness Races in Orbit Avatar answered Jan 11 '23 03:01

Lightness Races in Orbit


<< 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&));
like image 27
haccks Avatar answered Jan 11 '23 03:01

haccks