CHAPTER 21

image

Custom Conversions

Custom type conversions can be defined to allow an object to be constructed from or converted to another type. In the following example, there is a class called MyNum  with a single integer field. With conversion constructors it is possible to allow integer types to be implicitly converted to this object’s type.

class MyNum{  public:    int value;};

Implicit Conversion Constructor

For this type conversion 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 ...

Get C++ 14 Quick Syntax Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.