Lesson 15 - Polymorphism in C++
In the previous lesson, A mage for the C++ arena, we created a mage. He can fight, but he's
not in the arena yet. We haven't added it to the arena because it can only
handle warriors so far. So in today's tutorial, we have to tell C++ that
Mage is really a warrior and can be treated like one.
Don't be scared of the obscure name of this technique, it's actually very
simple. Polymorphism allows us to use a unified interface to work with objects
of different types. Imagine that we have, for example, many objects representing
geometric shapes (circles, squares, triangles, and so on). It'd certainly be
helpful if we could communicate with them in some unified way even though
they're different. We can create a
GeometricShape class containing
color field and a
render() method. All the geometric
shapes would then inherit the interface from this class. Now you may be
thinking, "But the circle and square object would render differently!." Well,
polymorphism allows us to override the
render() method in every subclass so it
will do what we want. The interface will be unified and we won't have
to think about which method to call to render different objects.
Polymorphism is often explained using animals. All having a
speak() method in their interface, but each animal performs it
...End of the preview...
You've come here and that's great! We believe that the first lessons showed you something new and useful
Do you want to continue the course? Go to the premium section.
Limited offer: Learn all knowledge and save money
- Unlimited and permanent access to individual lessons.
- High quality IT knowledge.
- Skills to help you get your dream and well-paid job.
Requested article covers this content:
In this C++ tutorial, we'll look at one of the most difficult topics of object-oriented programming, polymorphism, and virtual methods.
You gain credits by supporting our network. This is done by sending a helpful amount of money to support the site, or by creating content for the network.