Quote:Original post by NUCLEAR RABBIT
Hello,
Im trying to understand polymorphism and I created a little program to try and illustraight its usage, but I've read that polymorphism is used for less typing, but in my example program, it seems like there is extra typing. Please help me, it feels like Im doing something wrong here.
NOTE: There are no errors, just design problems.
Your example looks fine; it illustrates the basic idea behind polymorphism nicely.
If anything, 'less typing' is just one of many possible side effects of using polymophism. It certainly isn't it's
raison d'etre, per se, so I wouldn't get too hung up on it.
I think as you explore polymorphism and inheritance further its uses and benefits will start to become more apparent. To get you started, I'll give one example based on what you posted. Since Dog and Cat inherit from a common base class with virtual functions, they can each be represented by and accessed via an Animal*, as your example shows. You could then, for example, maintain a container (list, vector, or what have you) of Animal*'s, and then decide
at run time whether these Animals will be Cats, Dogs, or both. Furthermore, you can re-assign the pointers to new objects of different types on the fly.
Throughout, the
interface remains the same. The code that iterates through the container and calls Eat(), Sleep(), and so on, doesn't know about or care about the actual type of the object on which it's being called. This may be what was meant by the 'less typing' comment; in many cases polymophism can take the place of multiple blocks of code, if/else sequences, or switch statements.
That's a very simplistic overview, but maybe it'll help clear things up a bit.