0

I have a base class (ANIMAL), a descendant class (BIRD) which adds method tweet. I pass an instance of bird to a method expecting a class ANIMAL.

How I can that method check if the passed in object implements method tweet?

This in C++ (with Qt5 in case that matters)

TSG
  • 3,545
  • 8
  • 45
  • 101
  • You cannot unless using a CRTP or virtual polymorphism. – πάντα ῥεῖ Jan 24 '16 at 14:30
  • What is the real problem you're trying to solve. No, not the one that you're asking, but the real problem for which you think the solution is to check if a subclass implements a particular method. – Sam Varshavchik Jan 24 '16 at 14:30
  • I need to pass objects into a class that MAY or MAY NOT offer particular features (i.e. methods). I only want to call those methods if the descendant added those features. – TSG Jan 24 '16 at 14:41
  • 1
    Try dynamic_cast - http://en.cppreference.com/w/cpp/language/dynamic_cast – Ed Heal Jan 24 '16 at 14:44
  • so I would have to use instanceof and check every possible descendant class type (and know which class implements which methods)? Seems tedious – TSG Jan 24 '16 at 14:54
  • You get a argument that has type animal. Just check if it is a bird. One line of code (assuming that you have a reasonable inheritance hierarchy – Ed Heal Jan 24 '16 at 14:59
  • 1
    Downcasting is a codesmell. You should probably go for composition over inheritance. – Andy Jan 24 '16 at 15:53
  • There's also [RTTI](http://stackoverflow.com/questions/17204487/checking-the-object-type-in-c11); but it's probably best addressed by re-thinking your design. – Brett Hale Jan 24 '16 at 16:03
  • Others have mentioned dynamic_cast and RTTI and suggested redesign which I agree with completely. However, FYI in it's purest form what you are talking about is reflection which is not generally possible in C++, but can be achieved if you are willing to put a great deal of effort into it. See [How can I add reflection to my C++ application](http://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application) – efunkh Jan 24 '16 at 21:23
  • I think I have to rethink my design (as you've suggested) - combined with dynamic_cast. Does that mean I define a pointer to the base class, then recast it to point to a descendant? – TSG Jan 24 '16 at 22:11
  • @Telium yes. The syntax will look like: child *p = dynamic_cast(pointerToBase). Keep in mind that if pointerToBase is not actually a child class, the dynamic_cast will fail and return nullptr. – efunkh Jan 25 '16 at 14:07

0 Answers0