virtual polymorphic functions

I kinda understand what virtual polymorphic functions are. What really confuses me, though, is that why one would want to use polymorphic functions.

So what's the purpose of virtual polymorphic functions?
Lets say you have a vector of Shape*, and those Shape* could actually be Rectangle* or Triangle* or whatever. You could just have a virtual draw() function so that you can simply iterate over that vector and call draw() without having to know the type of Shape you have.
Well, I could just define a seperate draw function in each of these sub classes.

Why do I have to put a virtual draw in the super class?
as an example (a good one I hope):

1. you declare a pointer to Shape (abstract class)

Shape * p;

2. now you can allocate memory on the free store and assign it to p with whatever type (subclass) you want

Both p = new Rectangle; and p = new Triangle; are correct.

3. then you can call the draw() function

p->draw() and you don't mind if you're drawing Rectangle or Triangle, the appropriate function will be called
Oh, so the draw() in the super class is just there, but doesn't really do any task? ...
Well, is that why they call it "virtual" ?
It's not so that it doesn't do any task. It allows you to use constructions mentioned above.

Well, is that why they call it "virtual" ?

Exactly.
Yeah.

The idea is that you can treat all related types the same way without your code having to realize they're actually different types.

You code can work with just general "Shapes" and not have to worry about whether those shapes are really circles, triangles, or whatever.
Topic archived. No new replies allowed.