I have this chunk of code:
struct A
{
operator int*() { return nullptr; }
};
int main()
{
A x;
x[42] = 42;
int z = x[42];
}
To my surprise, the following compiles. The implicit conversion takes place and conditionally converts A to int* and accesses the memory given by the pointer (I returned nullptr just for simplicity). As the reference says:
Implicit conversions are performed whenever an expression of some type T1 is used in context that does not accept that type, but accepts some other type T2; in particular:
- when the expression is used as an operand with an operator that expects T2
So, why does the following not work?
struct A
{
int operator[](int)
{
return 42;
}
};
struct B
{
operator A()
{
return A();
}
};
int main()
{
B x;
int z = x[42];
x[42] = 42;
}
The compiler says: error: no match for 'operator[]' (operand types are 'B' and 'int'). What am i missing?