Recently, I was browsing through my copy of the C++ Pocket Reference from O'Reilly Media, and I was surprised when I came across a brief section and example regarding user-defined conversion for user-defined types:
#include <iostream>
class account {
private:
double balance;
public:
account (double b) { balance = b; }
operator double (void) { return balance; }
};
int main (void) {
account acc(100.0);
double balance = acc;
std::cout << balance << std::endl;
return 0;
}
I've been programming in C++ for awhile, and this is the first time I've ever seen this sort of operator overloading. The book's description of this subject is somewhat brief, leaving me with a few unanswered questions about this feature:
- Is this a particularly obscure feature? As I said, I've been programming in C++ for awhile and this is the first time I've ever come across this. I haven't had much luck finding more in-depth material regarding this.
- Is this relatively portable? (I'm compiling on GCC 4.1)
Can user-defined conversions to user defined types be done? e.g.
operator std::string () { /* code */ }