title: C++: Custom data type - typecasting and union issues
body: <p>What I'm trying to do is create a new custom data type that behaves like all other primitive types.  Specifically, this data type appears like a Fixed Point fraction.
  I've created a class to represent this data type, called "class FixedPoint", and in it there are ways to typecast from "FixedPoint" to "int" or "double" or "unsigned int", etc.  That is fine.</p>
  
  <p>Now, what if I want to cast from <code>"int" to "FixedPoint"</code>?  Originally my solution was to have a constructor:</p>
  
  <pre><code>FixedPoint(int i) { /* some conversion from 'int' to 'FixedPoint' in here */ }
  </code></pre>
  
  <p>This works...but you cannot put it into a union like so:</p>
  
  <pre><code> union {
     FixedPoint p;
   };
  </code></pre>
  
  <p>This will break, because "FixedPoint" does not have an implicit trivial constructor (we just defined a constructor, "FixedPoint(int i)").</p>
  
  <p>To summarize, the whole issue is "we want to <code>cast from some type T to type FixedPoint without explicitly defining a constructor</code> so we can use our type FixedPoint in a union".</p>
  
  <p>What I think the solution is but cannot find any evidence online:
  Define an overloaded global typecast operator to cast from "int" to "FixedPoint".  </p>
  
  <p>Is there a way to do this without using class constructors?  I'd like to be able to use this class in a union.  What I've tried (in global scope):</p>
  
  <pre><code>operator (FixedPoint f, int a) { ... } //compiler complains about this is not a method or non-static.
  </code></pre>
  
  <p>And a little example to show unions don't like constructors (they like POD)</p>
  
  <pre><code>class bob
  {
    public:
      bob(int a) { m_num = a; }
    private:
      int m_num;
  };
  void duck()
  {
    union 
    {
      bob a;
    };
  }
  </code></pre>
  
  <p>This error seen in Visual Studio is:</p>
  
  <pre><code>error C2620: member 'duck::&lt;unnamed-tag&gt;::a' of union 'duck::&lt;unnamed-tag&gt;' has user-defined constructor or non-trivial default constructor
  </code></pre>
  
  <p>Any ideas?
  Thanks</p>