Q:

Switch statements with Classes

We are currently studying classes in my Computing Science class. Today, the teacher introduced us to Switch Statements and I had the following question which he wasn't sure of:

Can switch statements be used alongside classes if we overload the == operator?

A:

Exactly as you phrased the question: No. But it is possible to design a class that is compatible witch switch. This is an example using a barebones wrapper class for integers:
// Only possible in C++11 and newer.
class Integer
{
public:
    constexpr explicit Integer(int p) : m_payload(p) {}     // (1)
    constexpr operator int() const { return m_payload; }    // (2)

private:
    int m_payload;
};

int main()
{
    // For simplicity. This could be a user input or some other value
    // determined when running the program.
    Integer five(5);

    switch (five) {  // (4)
        case Integer(5):  // (3)
            return 0;
        default:
            return 1;
    }
}

I’m going to gloss over a lot of finer details. What the code does is this:

The value evaluated by the switch – in this case five in line (4) – must be either an integer-like value or implicitly convertible to an integer-like value. That’s what the operator int() (2) does – it’s called a conversion operator.
The cases of a switch must be constant integral expressions, i.e. they must must evaluate to an integer-like value and the evaluation must be possible at compile-time. To make line (3) work all of the following must be true:

An Integer object must be able to be created at compile-time. That is provided by the constexpr constructor in line (1). The constexpr is key here.
The object must be created with a value that’s actually known at compile time. That’s the literal 5 in line (3). You could not run your program, query the user for an integer and use that user input instead of the 5. The compiler has no way to anticipate the user’s input, after all.
An Integer object must be implicitly convertible to an integer-like value at compile time. That’s provided by the constexpr in like (2).

To sum up: Yes, you can design your own classes to be compatible with switch. But rather severe restrictions apply, and it has nothing to do with operator==().

