The point of using them is so that you can refer to subclass objects through a base class reference and have subclasses' functions have different meanings.
They are useful when you want to design objects that are related to each other.
Ultimately, it allows you to implement a function in different ways.
With virtual functions used, you make a pointer to a base class, and then you assign it to a subclass.
For example:
You might want to draw custom shapes to the screen in your API.
You might have a class named Shape, with virtual functions, and subclasses named Triangle, Rectangle, Circle, Rhombus, et cetera.
These subclasses will have to override the Draw() function defined in the Shape class, so they are drawn to the screen properly.
Now when you want to make a bunch of these shape objects, you can group them together into a vector of pointers to Shape objects.
You could then add any type of shape object to that vector like this:
Now you can call on all of the Shape objects in the vector like this:
Code: Select all
for (Uint32 i = 0; i < shapes.size(); i++)
shapes[i]->Draw();
So you might be wondering what's the difference between polymorphism and inheritance.
As Wikipedia says: "When a derived object is referred to as being of the base's type, the desired function call behavior is ambiguous."
This basically says that if you don't use virtual functions and try to do the above, the function will just call on the base class's function.