So are you saying they're really only meant for very rudimentary functions like speak(),walk(),draw(),etc.. with no parameters |
They're meant for functions that can apply to any/all derived types. The number of parameters has nothing to do with it. It's just that all of the examples you're seeing are simple =P
It's a conceptual thing. The base class 'Shape' represents a shape. It would have functions that do things which can apply to
any kind of shape. In the above example, I would want to be able to Draw any kind of shape.
However, for some tasks, you would need to know the specific kind of shape in order to perform it. That's where virtual functions come in handy. They let you call derived class functions without knowing exactly what the derived class is.
i'm guessing you have to leave the base class virtual function as generic as possible.
|
That's true in a sense. You only want the base class to do things that apply to ALL derived types. If your base class does something that only works with a specific derived type, it turns the code into a big mess.
For example, the code in Shape shouldn't assume that the shape is a Square, because it might not be. So no functions or anything should take any parameters or anything that is specific to a Square.
By the way- in your example you've made inherited classes like circle and square virtual?. i've read somewhere you only make the base class or first declaration of the function 'virtual'.
|
It doesn't matter. If it's virtual in the base class, it will be virtual in the derived class even if you omit the virtual keyword.
I choose to have the virtual keyword in my derived classes for additional clarity.
But either way works fine and has the same effect.