Michael
Michael

Reputation: 6899

C++ conversion operator error?

Operators overloaded within class declaration:

class Asdf{

    operator float() const;                 
    Asdf operator+(const Asdf&) const;
    Asdf operator+(float);

}

int main()

{
    Asdf object1, object2, object3;

    //Receiving error: "more than one operator '+' matches these operands"
    object1= object2 + object3;

    _getch();
    return 0;
}

Errors:

   :error C2666: 'Asdf::operator +' : 3 overloads have similar conversions

   :could be 'Asdf Asdf::operator +(float)'

   :'Asdf Asdf::operator +(const Asdf &) const'

When I remove all conversion used with the overloaded float conversion operator the code compiles properly.

Upvotes: 0

Views: 325

Answers (2)

stinky472
stinky472

Reputation: 6797

Implicit conversion operators tend to invite these kinds of ambiguities, especially when combined with implicit constructors.

From C++ Coding Standards:

  1. Consider overloading to avoid implicit type conversions.

Do not multiply objects beyond necessity (Occam's Razor): Implicit type conversions provide syntactic convenience (but see Item 40). But when the work of creating temporary objects is unnecessary and optimization is appropriate (see Item 8), you can provide overloaded functions with signatures that match common argument types exactly and won't cause conversions.

Not all change is progress: Implicit conversions can often do more damage than good. Think twice before providing implicit conversions to and from the types you define, and prefer to rely on explicit conversions (explicit constructors and named conversion functions).

A lot of this goes into efficiency and unexpected behaviors that can result from providing implicit conversions, but ambiguity errors from function overloading are included in the sort of side effects you can easily encounter when providing implicit conversion operators and/or constructors.

Solution: make your operator explicit or try to avoid providing it at all. It may be convenient, but it can invite nasty surprises like this (the compiler error is actually the least nasty).

Upvotes: 3

Qaz
Qaz

Reputation: 61900

This is happening because the conversion operator provides an implicit means from your class to a float. Thus, the other addition operators involving floats get in the way.

To remedy this, the best solution if you really want that conversion to be possible is to mark it explicit:

explicit operator float() const;

Asdf a;
float f = static_cast<float>(a);

However, this only works in C++11. In C++03, a better option would be to use a function instead:

float toFloat() const;

Asdf a;
float f = a.toFloat();

Upvotes: 3

Related Questions