Why does setting the array to my class not work (operator overloading)?

Pages: 12
The C++ standards document:
8.3.4 Arrays and also
8.5.2 Character arrays
Last edited on
@vlad from moscow,

So when initialized with a string literal, the variable of the array does not point to the first element, but holds a value of the literal?

@guestgulkan,

Cool, checking it out right now.
Last edited on
the variable of the array does not point to the first element, but holds a value of the literal?

The array holds the individual characters of the literal (which is also a character array).

The final C++ standard is not available for free, but earlier drafts are, which are mostly identical to the final version, like this one:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
Last edited on
@Athar,

Hmm.. lets say I'm working with this code.

1
2
3
4
5
6
int main()
{
    char example[] = "Hi";
    cout << example << "\n"; // will print "Hi"
    return 0;
}


Does this mean that example resolves to the literal it holds but example[0] resolves to H?
Does this mean that example resolves to the literal it holds but example[0] resolves to H?

Yes. But note that in this case, example is converted to a pointer, as the appropriate overload of operator<< takes const char* as a parameter and treats the pointer as if it was the beginning of a null-terminated character array (a.k.a. C string).
Last edited on
But how does a pointer point to a literal?
It points to the first character of the literal. The characters that follow after the first can be accessed via pointer arithmetic. That's why the fact that elements of an array are adjacent in memory is important - if you have a pointer to any element of the array (and if you know which one it is), you can calculate the address of all other elements.
Last edited on
Oh, sorry, it seems that the address of example is "Hi".
Last edited on
What. No. "Hi" is a string literal, not a memory address.
And "Hi" has nothing to do with the array example other than the fact that the characters of "Hi" are copied into the array example on initialization.
Topic archived. No new replies allowed.
Pages: 12