c++ - Inheritance resolution -
i thought types automatically resolve deepest part of hierarchy could. if cat : animal , call cat->talk(), if cat overrides talk() class animal, cat "meow", not weird general animal grumbling provided in base class animal.
so i'm confused this:
struct animal { virtual void talkto( animal* o ) { puts( "animal-animal" ) ; } } ; struct cat : public animal { virtual void talkto( animal* o ) { puts( "cat-animal" ) ; } virtual void talkto( cat* o ) { puts( "cat says meow cat" ) ; } } ; here's calling code:
cat *cat = new cat() ; cat->talkto( cat ) ; //cat says meow cat animal *animalcatptr = cat ; cat->talkto( animalcatptr ) ; //cat-animal the last line here, send cat cat->talkto, i'm using animalcatptr. animalcatptr still refers cat, yet resolving animal in function call.
how can make pass pointer resolve deepest type in hierarchy is? don't want series of dynamic_cast<> testing see if animal have on hand cat or dog or have you.
you want form of double-dispatch, see http://en.wikipedia.org/wiki/double_dispatch
Comments
Post a Comment