Dai Haoci
Dai Haoci

Reputation: 209

What is the best practice of type conversion overloading?

class A
{
public:
    A ( unsigned _a ) : a (_a)
    {
    }
    operator unsigned& () 
    {
        return a;
    }
    operator const unsigned () const
    {
        return a;
    }
    unsigned a; 
}; 

In the above example, I created two type conversion operators, one gives reference, one gives a copy. Both have drawbacks. Any suggestion?


Since type conversion operator is allowed in C++, how can we make best use of it and where?

Upvotes: 3

Views: 380

Answers (1)

Chad
Chad

Reputation: 19032

How about making the second one const as you're returning a copy anyway. That will remove the ambiguity:

class A
{
public:
    A ( unsigned _a ) : a (_a)
    {
    }
    operator unsigned& () 
    {
        return a;
    }
    operator unsigned () const // make this one const
    {
        return a;
    }
    unsigned a; 
}; 

Upvotes: 3

Related Questions