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...
ict.social is a large database made up of manuals and tutorials, whose main goal is to provide high-quality IT education to everyone. We started out in the Czech republic, where we display roughly a million articles per month and receive plenty of gratitude from our users. Thanks to our successful establishment, we are now bringing these articles to the rest of the world.
Although we are trying to keep our content free of charge, maintaining the site is a huge effort for everyone involved. Therefore, some content (exercises and more advanced material) costs network points. Don't worry, they're really cheap :)
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.
Buying this article gives you unlimited access to it forever. You will learn some more and help us keep giving our site maintenance which helps you and others get better futures. It's a win-win.
You gain points 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.
You can get points immediately using:
|Credit card||SMS||Wire transfer|