Conversion Operators

A conversion operator (also called a cast operator) can be used to convert an object of one class to another type. Such a conversion operator must be a non-static member function. The function prototype

MyClass::operator char *() const;

declares an overloaded cast operator function for converting an object of class MyClass into a temporary char * object. The operator function is declared const because it does not modify the original object. The return type of an overloaded cast operator function is implicitly the type to which the object is being converted. If s is a class object, when the compiler sees the expression static_cast<char *>(s), the compiler generates the call

s.operator char *()

to convert the operand

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.