Cosmin
Cosmin

Reputation: 131

Issue with operator overloading in c++

I seem to have a strange problem with the order my operators get called in my c++ program, i've created a class with some operators that throw exceptions based on their arguments:

class Variant
{
public:
..stuff..
Variant(int data) {..stuff..}
operator int() throw(...)
{
    if(type == 0)
        return value;
    else
        throw 0;
}
Variant operator +(Variant &v) throw(...)
{
    Variant res;
    if(type == 2) {
        res.value = v.value;
        res.svalue = v.svalue;
..stuff..
        else
            throw 0;
        res.type = type;
    }
    return res;
}
Variant operator *(Variant &v) throw(...) {..stuff..}
}
..stuff..
    int res1;
    Variant res, res2;
..stuff..
//          try {
            if(res1 < 0)

The issue is that on this next line the Variant::int() cast operator gets called on the variable res and throws an exception and the Variant::+ operator never gets called even though all the operands are Variants as far as i can see)

                res = res + Variant(res1) * res2;
            else

Whereas on this next line the correct Variant::+operator gets called and all is well

                res = res + res2;
//          } catch (...) {
//              error = "Invalid operator";
//              isok = false;
//  

I just noticed that simply putting the multiplication in a temporary variant variable (like tempv = Variant(res1) * res2) and doing it in two steps works, but i can't understand why. } Could anyone suggest what would cause the compiler to try and do an automatic cast to int ? Do i lack an operator or something ?

Upvotes: 0

Views: 78

Answers (2)

spin_eight
spin_eight

Reputation: 4025

"Variant::+ operator never gets called" - because this is the way as exceptions work, after exception is raised all the rest part of the try{} block is skipped and control goes to the catch(...){} block

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168616

Variant operator +(Variant &v)

should be

Variant operator +(const Variant &v)

The reason that your operator+ isn't being called is because the temporary created by Variant(res1) cannot bind to the non-const parameter Variant &v.

Upvotes: 3

Related Questions