title: C++ Overloading Conversion Operators
body: <p>I am trying to have a class that allows implicit casting to certain built in types, like unsigned long int and since I'm trying to do this as correct as possible (this is my first important project in C++), I have hit a strange issue regarding const correctness:</p>
  
  <p>This works:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  class CustomizedInt
  {
  private:
      int data;
  public:
      CustomizedInt();
      CustomizedInt(int input);
      operator unsigned long int () const
      {
          unsigned long int output;
          output = (unsigned long int)data;
          return output;
      }
  };
  
  CustomizedInt::CustomizedInt()
  {
      this-&gt;data = 0;
  }
  
  CustomizedInt::CustomizedInt(int input)
  {
      this-&gt;data = input;
  }
  
  int main()
  {
      CustomizedInt x;
      unsigned long int y = x;
  
      std::cout &lt;&lt; y &lt;&lt; std::endl;
  
      return 0;
  }
  </code></pre>
  
  <p>But this:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  class CustomizedInt
  {
  private:
      int data;
  public:
      CustomizedInt();
      CustomizedInt(int input);
      operator unsigned long int () const;
  };
  
  CustomizedInt::CustomizedInt()
  {
      this-&gt;data = 0;
  }
  
  CustomizedInt::CustomizedInt(int input)
  {
      this-&gt;data = input;
  }
  
  CustomizedInt::operator unsigned long()
  {
      unsigned long int output;
      output = (unsigned long int)data;
      return output;
  }
  
  int main()
  {
      CustomizedInt x;
      unsigned long int y = x;
  
      std::cout &lt;&lt; y &lt;&lt; std::endl;
  
      return 0;
  }
  </code></pre>
  
  <p>gives me this error in Visual Studio 2010: <code>error C2511: 'CustomizedInt::operator unsigned long(void)' : overloaded member function not found in 'CustomizedInt'</code></p>
  
  <p>Now, if I remove the keyword const from the operator definition, everything is OK. Is this a bug? I read that I'm supposed to use the const keyword after each (public) method / operator in order to clearly state that it does not alter the current object in any way.</p>
  
  <p>Also, I know that defining such an operator may be poor practice, but I am not sure I fully understand the associated caveats. Could somebody please outline them? Would it be better practice to just define a public method called ToUnsignedLongInt?</p>