A89: C, C++ and stuff (OT)


[Prev][Next][Index][Thread]

A89: C, C++ and stuff (OT)




----- Original Message -----
From: "Niklas Brunlid" <e96nbr@efd.lth.se>
> I just need to ask: if this is true, then how does the << operator handle
all
> the other datatypes you throw at it? Last time I looked, it handles
_everything_
> that printf handles - in fact, it handles more, since C++ supports
operator
> overloading.
> (Yes, I know what you meant with the C++ Statement vs printf(), but see
below).

As far as I know, this is done at compile time. so a line like
cout << "a string" << 42 << "another string" << 3.303;
would result in something like

cout::operator<<("a string");  /// call to operator<<(char*)
cout::operator<<(42); /// call to operator<<(int)
cout::operator<<("another string"); /// call to operator<<(char*)
and so on.

(not entirely true, but anyway. The cout::operator<< returns a refernce to
itself that the next << uses and stuff like that)

It looks on the type of the argument and chooses a function that matches
that. If it can't find an exact match, it checks if it can find a function
that accepts something that it can convert the argument to. (like the
function accepts a const char* but the argument is char*. no problem, its
compatible. or the argument is a "string" (new standard type (an object))
that has a rule for converting itself to a char*... If this also fails, it
spits out an error message in the linking.
This is actually implemented useing operator overloading.

so in this way cout produces larger code then the same thing in C, since
printf("a string%ianotherstring%f",42,3.303);
or whatever would only produce a single function call.
But that is still in the implementation of the standard stuff, not in C or
C++ itself really. (I know, it is easy to think about the standard stuff as
a part of the actual programming language, and it is convenient to say it is
when you teach it, since it could get confuseing otherwise, but it still
really isn't part of it.)
you don't _have_ to use cout just because you program C++, you could use
printf (or something named printf that works like printf) just as well.

///Olle




References: