This documentation is archived and is not being maintained.

20.2.1 Convert-From Operators

Visual Studio .NET 2003

These are so-named since they create an object of the class in which the operator is defined from an object of some other class.

Standard C++ does not support convert-from operators other than by direct calls. They are not called by any cast syntax or via implicit conversion. It uses constructors for this purpose. The Managed Extensions provide syntactic support for calling convert-from operators. They need to be called directly.

To interoperate well with other CLS-compliant languages, the user may wish to wrap each user-defined unary constructor for a given class with a corresponding convert-from operator.

Constraints

A convert-from method is defined like a normal C++ method, following the rules for common language runtime conversion operators:

  • They shall use static methods.
  • They shall be named op_Implicit or op_Explicit. op_Implicit should be used for conversions that do not lose precision such as short-to-int. op_Explicit should be used for the converse case.
  • They shall return an object of the containing class.
  • The "from" type shall be the sole parameter type.

Convert-from methods must be called in the same way as ordinary methods.

Example

// managed_operators4.cpp
// compile with: /clr
#using <mscorlib.dll>

__value struct MyDouble {
   double d; 
   MyDouble(int i) { d = (double) i; }
   // Wrap the constructor with a convert-from operator.
   // Use op_Implicit because it does not lose precision.
   static MyDouble op_Implicit(int i) {
      MyDouble d(i);
      return d;
   }
};

int main() {
   int i = 10;
   MyDouble md = MyDouble::op_Implicit(i);
}
Show: