News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

C++ Tutorial – 22 – Custom Conversions

This chapter covers how custom type conversions for an object can be defined. In the example below, there is a class called MyNum with a single integer field. With custom type conversions it is possible to allow integer types to be implicitly converted to this object’s type.

class MyNum
{
 public:
  int value;
};

Implicit conversion methods

For this to work a constructor needs to be added that takes a single parameter of the desired type, in this case an int.

class MyNum
{
 public:
  int value;
  MyNum(int i) { value = i; } 
};

When an integer is assigned to an object of MyNum this constructor will implicitly be called to perform the type conversion.

MyNum a = 5; // implicit conversion

This means that any constructor that takes exactly one argument can be used both for constructing objects and for performing implicit type conversions to that object type.

MyNum b = MyNum(5); // object construction
MyNum c(5);         // object construction

These conversions will not only work for the specific parameter type, but also for any type that can be implicitly converted to it. For example, a char can be implicitly converted to an int and can therefore be implicitly changed into a MyNum object as well.

MyNum d = 'H'; // implicit conversion (char->int->MyNum)

Explicit conversion methods

To help prevent potentially unintended object type conversions it is possible to disable the second use of the single parameter constructor. The explicit constructor modifier is then applied, which specifies that the constructor may only be used for object construction, and not for type conversion.

class MyNum
{
 public:
  int value;
  explicit MyNum(int i) { value = i; }
};

The explicit constructor syntax must therefore be used to create a new object.

MyNum a = 5;        // error
MyNum b(5);         // allowed
MyNum c = MyNum(5); // allowed
Recommended additional reading:
Sams - Teach Yourself C++ in One Hour a Day