Ich habe den folgenden Code (vereinfacht):Wie ruft man eine Methode und die Kindklasse auf, wenn das Argument vom Typ Elternklasse in C++ ist?
#include <cstdio>
class parent
{
public:
virtual void do_something() const
{
printf("hello I'm the parent class\n");
}
};
class child : public parent
{
public:
virtual void do_something() const
{
printf("hello I'm the child class\n");
}
};
void handle(parent p)
{
p.do_something();
}
int main()
{
child c;
handle(c);
return 0;
}
Dies druckt hello I'm the parent class
, auch wenn ich ein Argument vom Typ child
geben. Wie kann ich C++ sagen, dass es sich wie Java verhält und die Methode des untergeordneten Elements aufruft, indem es hello I'm the child class
druckt?
"Base" -Klasse ist der noch häufiger verwendete Begriff. –