Conversion Functions

To convert a single value to a class type, you create a class constructor that has the following prototype:

c_name(type_name value);

Here c_name represents the class name, and type_name represents the name of the type you want to convert.

To convert a class type to some other type, you create a class member function that has the following prototype:

operator type_name();

Although this function has no declared return type, it should return a value of the desired type.

Remember to use conversion functions with care. You can use the keyword explicit when declaring a constructor to prevent it from being used for implicit conversions.

Get C++ Primer Plus 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.