Is this correct (MI and overloading)
Ramadass, Ramanathan
Ramanathan.Ramadass@spirentcom.com
Tue Nov 4 02:39:00 GMT 2003
It is correct C++(as confirmed with the tests that you did on other compilers). For matching within a hierarchy, the longest leg i.e. the most specific type is always tried first. When there is more than one conversion to the same level, you have an ambiguity(as you saw when you defined "void f(C*)"). The situation is the same when you have only "void f(A*)" defined; you now have two equivalent paths and hence an ambiguity.
btw - this rule is exploited in a technique called "Base class composition" when using MI and virtual bases(see "scientific and engineering c++" by barton & nackman).
Thanks
Ram
-----Original Message-----
From: ZhenYu Hou [mailto:hou_zhenyu@hotmail.com]
Sent: Monday, November 03, 2003 5:37 PM
To: gcc-help@gcc.gnu.org
Subject: Is this correct (MI and overloading)
// Code begin
#include <stdio.h>
class A {
public:
A(char c) : c(c) {}
void print() { printf("from %c\n", c); }
private:
char c;
};
class B : public A {
public:
B() : A('B') {}
};
class C : public A {
public:
C() : A('C') {}
};
class D : public B, public C {
};
void f(A* a) {
a->print();
}
void f(B* b) {
b->print();
}
//void f(C* c) {
// c->print();
//}
int main() {
D d; // ambiguious ??
f(&d);
}
// Code end
The above code passed compilation of gcc3.3 (also vc7 and bcc5.5.1) and
printed "from B". However, if I remove the commert for "void f(C* c)" or
comment the function "void f(B* b)" out, the compiler will report error on
the line "D d;".
It seems that introduce an overloaded function can resolve ambiguity, made
the compiler know which path to convert from the most derived class to base
(in this case, add void f(B*) made the compiler implicitly select D->B->A).
Is this correct or a bug? Could anyone tell me?
Best regards
hzy
_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8.
http://join.msn.com/?page=features/junkmail
More information about the Gcc-help
mailing list