Sum between ADT and primitive type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Int {
    int i;
    
public:
    Int(int i = 0);
    friend Int operator + (Int, Int);
    operator int () const;
    int iVal();
};

Int::Int (int a) : i(a)
{
    
}

Int operator + (Int a, Int b)
{
    return a.i + b.i;
}

Int::operator int () const
{
    return i;
}

int Int::iVal()
{
    return i;
}

int main(int argc, const char * argv[])
{
    Int a = 7;
    int c = 2;
    Int h = a + (Int)c;
    return 0;
}


Why does the sum work only with the casting?

In fact if I write
 
Int h = a + c;
I get this error: "Use of overloaded operator '+' is ambiguous (with operand types 'Int' and 'int')".
Because an Int can be converted to int and an int can be converted to an Int, the compiler cannot know whether it is supposed to use operator+(Int,Int) or operator+(int,int).
This is why you should avoid conversion constructors (make them explicit) and conversion operators (those can be explicit only in C++11).
Last edited on
Topic archived. No new replies allowed.