454,480 Members | 1,711 Online
Need help? Post your question and get tips & solutions from a community of 454,480 IT Pros & Developers. It's quick & easy.

# operator const char*()

 P: n/a struct C { operator const char*() { return "...."; } }; int main() { C a; 0[a]; } Why does that 0[a] call operator const char*() ? Nov 22 '05 #1
11 Replies

 P: n/a vineoff wrote: struct C { operator const char*() { return "...."; } }; int main() { C a; 0[a]; } Why does that 0[a] call operator const char*() ? Not sure, but here's a guess. Take for example e1[e2]. This is exactly like *(e1 + e2). Since addition is commutative, this is the same as *(e2 + e1), which is again equivalent to e2[e1]. I suppose since the compiler cannot subscript an integer, it reverses the subscript, making it a[0]; and converts 'a' to a const char*. Jonathan Nov 22 '05 #2

 P: n/a In c language, a[0] and 0[a] is equivalent. Nov 22 '05 #3

 P: n/a Yes, a[0] calls that operator too, but why? Nov 22 '05 #4

 P: n/a vineoff wrote: Yes, a[0] calls that operator too, but why? How else would the compiler resolve the [] operator? Your struct C has none defined, so the only way is to convert C to a const char* and then use operator[] for that type. Nov 22 '05 #5

 P: n/a Why is it const char*, why not i.e. int ? Nov 22 '05 #6

 P: n/a vineoff wrote: Please quote the message you are answering to. Why is it const char*, why not i.e. int ? Why would it be an int? The compiler tries many different ways to accomodate what you type. With class C { public: operator const char*(); }; int main() { C c; c[0]; } the compiler checks whether c 1) is a pointer, or 2) has a class type which defines operator[], or 3) has a class type which can be converted to another type which is either 1), 2) or 3) (non exhaustive) Your class C is case 3). It is converted to const char* which is a pointer. Jonathan Nov 22 '05 #7

 P: n/a vineoff wrote: Why is it const char*, Because that's the conversion you provided. You didn't define any other. why not i.e. int ? int cannot be dereferenced, but a pointer can. And also, you didn't provide a conversion to int. Nov 22 '05 #8

 P: n/a Okay. Next question. struct C { operator int*() { int a = 54; return &a; } }; int main() { C a; std::cout<

 P: n/a vineoff wrote: Okay. Next question. struct C { operator int*() { int a = 54; return &a; } }; int main() { C a; std::cout<

 P: n/a vineoff wrote: Okay. Next question. struct C { operator int*() { int a = 54; return &a; } }; int main() { C a; std::cout< struct C { int operator[](int) const { return 54; } }; int main() { C a; std::cout << a[0] << a[0]; } Greg Nov 22 '05 #11

 P: n/a Yes of course, the point wasn't actually that. Nov 22 '05 #12

### This discussion thread is closed

Replies have been disabled for this discussion.