Thursday, October 27, 2016

What operator int() means in C++?

Short answer to the title of this post: It's a user-defined conversion to int.
Long answer: read on ;-).  The code below is a sample of the user-defined conversion. 
class MyClass {
   operator HANDLE() const { return(m_hCJ); }

   HANDLE m_hCJ;          // handle to volume


The code above would return MyClass object's m_hCJ member value if a conversion to HANDLE type is requested. For example:
MyClass testClass;
HANDLE testHandle = testClass;
In the preceding code, testClass operator HANDLE() will be called (at runtime?) to return testClass.m_hCJ value.

For more comprehensive example and explanation, see:

I brought this issue up because it uses the C++ operator keyword which is usually used for operator overloading. It could confuse those who hasn't seen C++ code that uses user-defined conversion.
Post a Comment

No comments: