Alternative to dynamic casting

c++, dynamic

Solution

C++ doesn't support sending messages as, e.g., Objective C or Smalltalk do. To call a method you need to have a statically typed handle for an object supporting the method. Whether you need to use a `dynamic_cast<Cat*>(pointer)` or if you can get away with something else, e.g., a `static_cast<Cat*>(pointer)` is a separate question.

Since `dynamic_cast<...>()` is relatively expensive and trying a potentially unbounded number of different classes isn't feasible, it may be preferable to use a `visit()` method in the base class which is called with a visitor. However, these are just techniques to get hold of a properly typed reference.

Problem

Is there an alternative to using `dynamic_cast` in C++? For example, in the code below, I want to be able to have `Cat` objects purr. But only `Cat` objects and not `Dog` objects. I know this goes against deriving the class from `Mammal` since it's not very polymorphic, but I still want to know if I can do this without `dynamic_cast`. My class declarations ``` class Mammal { public: virtual void Speak() const {cout << "Mammals yay!\n";} }; class Cat: public Mammal { public: void Speak() const{cout << "Meow\n";} void Purr() const {cout <"rrrrrrrr\n";} }; class Dog: public Mammal { public: void Speak() const{cout << "Woof!\n";} }; ``` In Main ``` int main() { Mammal *pMammal; pMammal = new Cat; pMammal->Purr(); //How would I call this without having to use dynamic_cast? return 0; } ```

Original source