I am trying to create a class that allows for implicit casting of some built-in types, such as unsigned long int, and since I am trying to make it as correct as possible (this is my first important C ++ project), I have got into a strange problem regarding correctness const:
It works:
#include <iostream> 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->data = 0; } CustomizedInt::CustomizedInt(int input) { this->data = input; } int main() { CustomizedInt x; unsigned long int y = x; std::cout << y << std::endl; return 0; }
But this:
#include <iostream> class CustomizedInt { private: int data; public: CustomizedInt(); CustomizedInt(int input); operator unsigned long int () const; }; CustomizedInt::CustomizedInt() { this->data = 0; } CustomizedInt::CustomizedInt(int input) { this->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 << y << std::endl; return 0; }
gives me this error in Visual Studio 2010: error C2511: 'CustomizedInt::operator unsigned long(void)' : overloaded member function not found in 'CustomizedInt'
Now, if I remove the const keyword from the operator definition, everything is fine. This is mistake? I read that I should use the const keyword after each (public) method / statement to clearly state that it does not modify the current object in any way.
Also, I know that defining such an operator can be bad practice, but I'm not sure I fully understand the warnings associated with it. Can someone please outline them? Would it be better if you just define a public method called ToUnsignedLongInt?
source share