Search code examples
c++operators

Why does declaring an `operator bool() const` member overload the [] operator?


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";
}

Solution

  • 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.