title: C++ Defining a type cast
body: <p>Is there a way to define a type cast from say a user defined class to a primitive type (int, short, etc.)? Also, would any such mechanism require an explicit cast, or would it work implicitly?</p>
  
  <p>for example:</p>
  
  <pre><code>// simplified example class
  class MyNumberClass
  {
  private:
      int value;
  public:
      // allows for implicit type casting/promotion from int to MyNumberClass
      MyNumberClass(const int &ampv)
      {
          value = v;
      }
  };
  </code></pre>
  
  <pre><code>// defined already above
  MyNumberClass t = 5;
  
  // What's the method definition required to overload this?
  int b = t; // implicit cast, b=5.
  // What's the method definition required to overload this?
  int c = (int) t; // C-style explicit cast, c=5.
  // ... etc. for other cast types such as dynamic_cast, const_cast, etc.
  </code></pre>