Code Yarns โ€๐Ÿ‘จโ€๐Ÿ’ป
Tech Blog โ– Personal Blog

Conversion functions in C++

๐Ÿ“… 2020-Jan-22 โฌฉ โœ๏ธ Ashwin Nanjappa โฌฉ ๐Ÿ“š Archive

C++ 11 and later versions of the language allow member functions to be defined as conversion functions. A conversion function is applied by C++ to convert the object to a specified type. In effect, it allows you to define one or more casts from your class object to other types.

The syntax and usage of conversion functions is demonstrated in this example:

#include <iostream>
#include <string>

struct A
{
    explicit operator int ()
    {
        std::cout << "convert-to-int\n";
        return 4;
    }

    operator std::string ()
    {
        std::cout << "convert-to-str\n";
        return "A object";
    }
};

int main()
{
    A a;
    int i = static_cast<int>(a);  // static_cast needed due to explicit
    std::string s = a;

    return 0;
}

Reference: ยง12.3 Conversions, C++11 standard