Cam
Cam

Reputation: 15234

Converting from a const user-defined class to a builtin type in C++

I have a class whose only data member is a 32 bit unsigned integer. That is, the class looks like this:

class A {
protected:
    unsigned int bits;
    /* ... some methods ... */
public:
    /* ... some methods ... */
};

But I want it to also be able to implicitly convert to and from 32 bit unsigned integers. So I added in a copy constructor as well as a casting operator:

class A {
protected:
    unsigned int bits;
    /* ... some methods ... */
public:
    A(): bits(0) {} // default constructor
    A(const unsigned int i): bits(i) {} // convert from unsigned int to A
    operator unsigned int() { return bits; } // convert from A to unsigned int
    /* ... some methods ... */
};

So now for example, I can do the following things:

int main () {
    // default constructor
    A a0 = A();
    // convert from unsigned int
    A a1 = 1 + 2;
    // conversions between the two types:
    unsigned int result = (a0 & a1 + 5) / 2;
}

However I'm struggling to get it to work with const types. In particular, the following doesn't work:

int main () {
    const A a = 5;      // works
    unsigned int i = a; // compiletime error
}

It says "No suitable conversion function from 'const A' to 'unsigned int' exists.". I'm using Visual Studio 2010 with the default compiler as provided by microsoft.

What conversion function do I need to create for it to work properly?

Upvotes: 0

Views: 1241

Answers (1)

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

Declare the conversion operator const:

operator unsigned int() const { return bits; }

Caveat: Implicit conversion operators are almost always a bad idea. The dangers usually far outweigh the minor inconvenience of calling a plain old member function:

unsigned int asInt() const { return bits; }
⋮
unsigned int i = a.asInt();

The ultimate solution, if you have C++11, is to declare an explicit conversion operator:

explicit operator unsigned int() const { return bits; }
⋮
unsigned int i = static_cast<int>(a);

Upvotes: 3

Related Questions