📅 2020-Jan-22 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cast, conversion function, cpp ⬩ 📚 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