Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass child class to method as parent class [closed]

Tags:

c++

oop

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!

like image 987
milanseitler Avatar asked Sep 13 '25 22:09

milanseitler


1 Answers

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.

like image 80
SomeWittyUsername Avatar answered Sep 16 '25 12:09

SomeWittyUsername