0

I am working with some classes that were generated by someone else. Below is a section of the class, I have removed most of it because it is not relevant for this question

struct OrderStatus {
    enum Value {
        New             = (char)48,
        PartiallyFilled = (char)49,
        Filled          = (char)50,
        Cancelled       = (char)52,
        Replaced        = (char)53,
        Rejected        = (char)56,
        Expired         = (char)67,
        Undefined       = (char)85,
        NULL_VALUE      = (char)0
    };

private:
    Value m_val;

public:
    explicit OrderStatus(int    v) : m_val(Value(v))   {}
    explicit OrderStatus(size_t v) : m_val(Value(v))   {}
    OrderStatus()                  : m_val(NULL_VALUE) {}
    constexpr OrderStatus(Value v) : m_val(v) {}

    operator Value() const { return m_val; }
};

Two questions:

  • What does operator Value() do?

  • I will be working with an instance of this class and want to do a switch on that instance's m_val but that is private. Is this possible?

asimes
  • 5,749
  • 5
  • 39
  • 76
  • 1
    Please only asking one question per post. The overloaded operator is an *implicit* [conversion operator](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading/16615725#16615725). You will only be able to access `m_val` from member or friend functions. Note also that the `(char)` casts used in `OrderStatus::Value` are pointless since untyped enums will have `int` sized regardless of their possible values. Use a typed enum if you care about space. – Brian61354270 Mar 05 '20 at 20:34
  • 1
    But fortunately you can get the value of `m_val` through the conversion operator. – BlameTheBits Mar 05 '20 at 20:36

1 Answers1

2

As pointed out in the comments, the Value() operator is an implicit conversion operator; because of this member, you can just use an instance of the OrderStatus class in order to use its (otherwise inaccessible) m_val member. You would use this as a variable of the enum type OrderStatus::Value.

Here is a short example of using it in a switch:

#include <iostream>
//
// Insert the code from your question here!
//
int main()
{
    OrderStatus q(48);
    switch (q) {
        case OrderStatus::New:
            std::cout << "New";
            break;
        default:
            std::cout << "Something else!";
    }
    std::cout << std::endl;
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83