I have a question about an unexpected conversion:
class BadString
{
public:
BadString(char const*);
...
char& operator[] (size_t); //(1)
char const& operator[] (size_t);
operator char* (); //(2)
operator char const* ();
};
int main()
{
BadString str("correkt");
str[5] = 'c'; //possibly an overload resolution ambiguity !!!
}
The explanation goes like this:
The subscript operator at (1) seems like a perfect match. However is not quite perfect because the argument 5 has type int, and the operator expects size_t (unsigned int or unsigned long, but never int). Still, a simple standard integer conversion makes (1) easily viable. However, there is another candidate: the built-in subscript operator. Indeed, if we apply the conversion operator (2) to str, we obtain a pointer type, and now the the built-in subscript operator applies. This operator takes a ptrdiff_t argument, which on many platforms is equivalent to int.
I understand that the original parameters for (1) was not matched, and then an implicit conversion will take place, but I don't understand why the compiler will try to convert str, using (2).
Thank you.
operator[]by return type. - juanchopanzachar const& operator[] (size_t)constant, e.g.char const& operator[] (size_t) const;- Some programmer dudeoperator char *is a bad idea anyway - Slava