Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ambiguity with conversion operator and constructor

I am learning c++, faced a problem with conversion operator. I am creating a complex class that can do basic operations on complex number.

class complex
{
    double real, img;

public:
    complex(double re=0,double im=0){
        real = re;
        img = im;
    }
    double get_real() const{
        return real;
    }
    double get_img() const{
        return img;
    }

};

I overloaded + operator:

complex operator+(complex a,complex b){
    return complex(a.get_real()+b.get_real(),a.get_img()+b.get_img());
}

With this code addition with double/integer with complex number works fine because of the constructor.

complex a(2,4);
complex b = 1+a;

But when I use a conversion operator inside the class

operator int(){
    int re = real;
    return re;
}

Addition with double/int stooped working

b = 1 + a;
// ambiguous overload

This seems weird, can anyone please explain how adding the conversion operator is creating this ambiguity?
I could not find any resource online.

like image 445
user136782 Avatar asked May 12 '26 09:05

user136782


1 Answers

In this expression statement

b = 1 + a;

either the operand 1 can be converted to the type complex using the conversion constructor or the object a can be converted to the type int using the conversion operator.

So there is an ambiguity between two binary operators +: either the built-in operator for the type int can be used or the user-defined operator for the type complex can be used.

To avoid the ambiguity you could for example declare the conversion operator as explicit.

 explicit operator int() const {
        int re = real;
        return re;
    }
like image 178
Vlad from Moscow Avatar answered May 14 '26 23:05

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!