Mar 12, 2010 at 5:50am UTC
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?
Mar 12, 2010 at 6:00am UTC
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.
Mar 12, 2010 at 6:13am UTC
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?
Mar 12, 2010 at 7:49am UTC
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
Mar 12, 2010 at 3:28pm UTC
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" ?
Mar 12, 2010 at 3:54pm UTC
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.