CHAPTER 21

image

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 ...

Get C++ Quick Syntax Reference 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.