eltsames Verhalten beim Aufruf virtueller Funktion
Ich verstehe nicht, was mit diesem Code falsch ist. Es sieht aus wie eine unglaubliche Falle!
Dieser Code:
class Foo
{
public:
virtual double foo(double x) const = 0;
double foo(int x) const { return (double)(x + x); }
};
class Bar : public Foo
{
public:
virtual double foo(double x) const { return x * x; }
};
int main()
{
Bar* b = new Bar;
Foo* f = b;
std::cout << b->foo(3) << " " << f->foo(3) << std::endl;
std::cout << b->foo(5.0) << " " << f->foo(5.0) << std::endl;
return 0;
}
druckt die folgende Ausgabe:
9 6
25 25
Ich folgere, dassBar::foo(double) const
wird mit einer impliziten Umwandlung aufgerufen, wenn der Typ des Zeigers @ isBar*
. AberWarum ist so etwas ohne Vorwarnung möglich?
Ich arbeite mit GCC 4.7.2. Ich habe mit @ kompilieg++ -Wall foobar.cpp -o foobar.exe