R
Richard Hayden
Hi,
I have the following code for example:
/**********************************/
#include <iostream>
class C1 {
public:
int a;
C1(int b) : a(b) { }
int operator+(C1& o) {
std::cout << "C1 Op+ CALLED";
return a + o.a;
}
};
class C2 : public C1 {
public:
C2(int b) : C1(b) { }
operator int() const { return a; }
int operator+(int o) {
std::cout << "C2 Op+ CALLED";
return o + a;
}
};
int main(int argc, char** argv) {
C2 o1(2);
C2 o2(3);
C2 o3 = o1 + o2;
return 0;
}
/**********************************/
Surprisingly this compiles (with g++) and outputs 'C2 Op+ CALLED'.
However, surely this should not compile since the call to operator+ is
surely ambiguous? int operator+(int o) called with an O2 requires one
cast (C2 -> int, which is defined explicitly in the class) and so does
int operator+(C1& o) (C2& -> C1&). What's going on here? Have I
misunderstood function overload resolution? Is g++ implementing the
standard incorrectly?
Thanks,
Richard Hayden.
I have the following code for example:
/**********************************/
#include <iostream>
class C1 {
public:
int a;
C1(int b) : a(b) { }
int operator+(C1& o) {
std::cout << "C1 Op+ CALLED";
return a + o.a;
}
};
class C2 : public C1 {
public:
C2(int b) : C1(b) { }
operator int() const { return a; }
int operator+(int o) {
std::cout << "C2 Op+ CALLED";
return o + a;
}
};
int main(int argc, char** argv) {
C2 o1(2);
C2 o2(3);
C2 o3 = o1 + o2;
return 0;
}
/**********************************/
Surprisingly this compiles (with g++) and outputs 'C2 Op+ CALLED'.
However, surely this should not compile since the call to operator+ is
surely ambiguous? int operator+(int o) called with an O2 requires one
cast (C2 -> int, which is defined explicitly in the class) and so does
int operator+(C1& o) (C2& -> C1&). What's going on here? Have I
misunderstood function overload resolution? Is g++ implementing the
standard incorrectly?
Thanks,
Richard Hayden.