Thursday, December 18, 2008

Operator overloading

What does the following program output?

#include <iostream>

int main(int argc, char **argv)
{
volatile char *p = "hello";
std::cout << p << '\n';
return 0;
}

6 comments:

Unknown said...

assuming it's not the obvious, I have no idea.

*goes to compile it*

what the hell???

Илья Казначеев said...

t.cpp: In function ‘int main(int, char**)’:
t.cpp:5: error: invalid conversion from ‘const char*’ to ‘volatile char*’

Anonymous said...

Evil, it emits evil.

Anonymous said...

1, because the only match is operator << (bool) since the volatile char * can't be implicitly converted to use a char * overload, but a pointer can be converted to a bool.

Yuri Chebotarev said...

nice gotcha.
but...
VS 2008:
warning C4800: 'volatile char *' : forcing value to bool 'true' or 'false' (performance warning)

the same but more obvious:
void foo(char* p){std::cout << p << '\n';}
void foo(bool p){std::cout << p << '\n';}

int _tmain(int argc, _TCHAR* argv[])
{
const char* p1 = "hello";
foo(p1);
return 0;
}

C++ is like a poison. it can be a cure if you know the proportion...otherwise it kills...

BadTux said...

This is an example of why I'm glad Linus Torvalds looked at recoding the Linux kernel into C++, said "ewwww!", and abandoned the notion immediately. In the past ten years of Linux programming I've needed to write C++ code... err. Not at all. Plenty of "C". Lots of Python. A fair amount of Java and Ruby and Perl and /bin/sh with its pals (awk, sed, etc.). But C++ is pure incarnated evil. Or is that instantiated?

That said, I once spec'ed out a project that had to be written in C++, so I do know it has a place. Said project could have been written in "C" but not with the schedule and resources that I was proposing to the funding people, and any higher-level language like Java or Python would have been either a) too slow, or b) unable to interact on a low-enough level with the OS to do what we needed to do. Still. The language is an atrocity. If Sun had not gone all stupid with Java and allowed Java to breathe so that people could add system-level features and easy compilation to machine code to the language instead of suing everybody who tried to extend the language to address low-level OS concerns (like they sued Microsoft), C++ would be consigned to the dustbin of history with PL/1, Algol-68, and other such monstrosities (well maybe not -- I suspect it'd be more like COBOL, something still around simply because it was "the standard" for so many years). Alas, Sun had to be stupid with Java... so it goes. (Shakes head at stupidity of it all).