class Method {
public:
virtual void Rum();
};
class Euler : public Method {
virtual void Rum() {
printf("ahoj\n");
}
};
class Kutta : public Method {
virtual void Rum() {
printf("ahoj2\n");
}
};
class Simulator {
public:
Method *pointer;
Simulator();
void setmethod(Method m) { pointer = &m; }
};
int main() {
Simulator s;
s.setmethod(new Kutta());
s.pointer->Rum();
s.setmethod(new Euler());
s.pointer->Rum();
}
I hope this example understandable enough. I tried to apply the principle of inheritance but I get these errors: (OOP stuff seems to be a little bit messed in my head)
prog.cpp: In function ‘int main()’:
prog.cpp:26: error: no matching function for call to ‘Simulator::setmethod(Kutta*)’
prog.cpp:21: note: candidates are: void Simulator::setmethod(Method)
prog.cpp:28: error: no matching function for call to ‘Simulator::setmethod(Euler*)’
prog.cpp:21: note: candidates are: void Simulator::setmethod(Method)
So what is the correct way to pass child instead of its parent? Thanks!
Signature of your void setmethod(Method m)
isn't correct. It must be void setmethod(Method* m)
to match your invocation.
As a side note, you need a reference or a pointer in your method for the polymorphism to work - that means that you can't pass the argument to setmethod
by value and expect the polymorphism to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With