Conversion functions (C++ only)

You can define a member function of a class, called a conversion function, that converts from the type of its class to another specified type.

Read syntax diagramSkip visual syntax diagram
Conversion function syntax

>>-+-----------+--operator--conversion_type--------------------->
   '-class--::-'                              

>--+----------------------+--(--)--+----------+----------------->
   | .------------------. |        +-const----+   
   | V                  | |        '-volatile-'   
   '---pointer_operator-+-'                       

>--+---------------------+-------------------------------------><
   '-{--function_body--}-'   

A conversion function that belongs to a class X specifies a conversion from the class type X to the type specified by the conversion_type. The following code fragment shows a conversion function called operator int():
class Y {
  int b;
public:
  operator int();
};
Y::operator int() {
  return b;
}
void f(Y obj) {
  int i = int(obj);
  int j = (int)obj;
  int k = i + obj;
}

All three statements in function f(Y) use the conversion function Y::operator int().

Classes, enumerations, typedef names, function types, or array types cannot be declared or defined in the conversion_type. You cannot use a conversion function to convert an object of type A to type A, to a base class of A, or to void.

Conversion functions have no arguments, and the return type is implicitly the conversion type. Conversion functions can be inherited. You can have virtual conversion functions but not static ones.