1

Why does this code compile? Since no operator[] is declared, I'd expect it to fail. Where is the operator[] definition coming from?

struct Test {
    operator bool() const {
        return true;
    }
};

int main(int argc, char** argv) {
    Test test;

    if (test["wut"])
        cout << "Success (test[\"wut\"])\n";
}
Chris
  • 325
  • 1
  • 3
  • 11
  • Those other questions may have the same answer, but they are definitely not the same question or else I would have found them. – Chris May 02 '23 at 04:11

1 Answers1

1

The operator is coming from the built-in subscript operator which treats expressions A[B] as *(A + B).

In these cases, test is being implicitly converted to an integer type of value 0 or 1 through the operator bool() method (1 for all of these cases).

This results in the evaluation of *(1 + "wut") => 'u', which then causes the if condition to pass, as 'u' is a non-zero value. Likewise, the following condition would also pass if ("wut"[test]) as this resolves to "wut"[1] => *("wut" + 1) => *("ut") => 'u'

Declare your member as explicit operator bool() to prevent your type from being implicitly converted to other integral types.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Chris
  • 325
  • 1
  • 3
  • 11