Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Defined Conversions in C++

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 */ }

like image 265
wash Avatar asked Jun 09 '10 18:06

wash


2 Answers

Is this a particularly obscure feature?

Yes, conversion operators aren't used very often. The places I've seen them are for user-defined types that can degrade to built-in ones. Things like a fixed-precision number class that supports converting to/from atomic number types.

Is this relatively portable?

As far as I know, it is. They've been in the standard forever.

Can user-defined conversions to user defined types be done?

Yes, that's one of the features of constructors. A constructor that takes a single argument effectively creates a conversion operator from the argument type to your class's type. For example, a class like this:

class Foo {
public:
    Foo(int n) {
        // do stuff...
    }
}

Let's you do:

Foo f = 123;

If you've used std::string before, odds are you've used this feature without realizing it. (As an aside, if you want to prevent this behavior, declare any single-argument constructors using explicit.)

like image 84
munificent Avatar answered Sep 23 '22 04:09

munificent


It's not particularly obscure; it is very portable (it is part of the language after all), and conversion to user-defined types is possible.

One word of caution, having a lot of possible implicit conversion paths can lead to unexpected conversion being invoked and surprising bugs. Also, having non-explicit converting constructors and conversion functions between several user-defined types can lead to more ambigious conversion sequeunces which can be a pain to resolve.

like image 21
CB Bailey Avatar answered Sep 22 '22 04:09

CB Bailey