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.

Conversion function syntax

1?  class ::  operator  conversion_type
1 +  pointer_operator
2  ( )
1 const
1 volatile
3?  { 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;
  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.