Re: Not sure how to describe behavior
* Scott McPhillips [MVP]:
"goodTweetieBird" <goodTweetieBird@hotmail.com> wrote in message
I stumbled onto this a while ago and I think I know what is happening
but I would like hear a more formal explanation. I am guessing it has
to do with multiple signatures in some class.
char s = "abcdef"
cout << s << endl; // prints abcdef
cout << *s << endl; // prints 'a'
That's expected behaviour. The type of s is char*
Sorry, that's incorrect; the type of s is char, an array.
That distinction is important in a number of situations, including use
of typeid, matching to reference formal argument, and doing such evil
things as 1+&s (note: casted to void* the result of 1+&s is in general
very different for s having type char and type char*).
so when you
dereference it (*s) you should get a char.
Informally, an array "decays" to a pointer to its first element in any
context where a pointer is required.
And it does that in both output statements in the example code above.
The reason that the first statement prints something other than the
pointer value is that this operator<< treats char* very differently from
other pointer types. It assumes it's a pointer to the first char of a
zero-terminated array of chars.
The "decay" (automatic conversion) is a big hole in the type system,
inherited from C. It worked nicely in C because C doesn't have
inheritance. But in C++ it means Derived x can be passed as actual
argument to a function expecting Base*, causing all sorts of problems.
Cheers, & hth.,
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
Q: What is the most annoying thing on usenet and in e-mail?