Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Beginning C++ Game Programming. - Second Edition

You're reading from  Beginning C++ Game Programming. - Second Edition

Product type Book
Published in Oct 2019
Publisher Packt
ISBN-13 9781838648572
Pages 746 pages
Edition 2nd Edition
Languages
Author (1):
John Horton John Horton
Profile icon John Horton

Table of Contents (25) Chapters

Preface 1. Chapter 1: C++, SFML, Visual Studio, and Starting the First Game 2. Chapter 2: Variables, Operators, and Decisions – Animating Sprites 3. Chapter 3: C++ Strings and SFML Time – Player Input and HUD 4. Chapter 4: Loops, Arrays, Switches, Enumerations, and Functions – Implementing Game Mechanics 5. Chapter 5: Collisions, Sound, and End Conditions – Making the Game Playable 6. Chapter 6: Object-Oriented Programming – Starting the Pong Game 7. Chapter 7: Dynamic Collision Detection and Physics – Finishing the Pong Game 8. Chapter 8: SFML Views – Starting the Zombie Shooter Game 9. Chapter 9: C++ References, Sprite Sheets, and Vertex Arrays 10. Chapter 10: Pointers, the Standard Template Library, and Texture Management 11. Chapter 11: Collision Detection, Pickups, and Bullets 12. Chapter 12: Layering Views and Implementing the HUD 13. Chapter 13: Sound Effects, File I/O, and Finishing the Game 14. Chapter 14: Abstraction and Code Management – Making Better Use of OOP 15. Chapter 15: Advanced OOP – Inheritance and Polymorphism 16. Chapter 16: Building Playable Levels and Collision Detection 17. Chapter 17: Sound Spatialization and the HUD 18. Chapter 18: Particle Systems and Shaders 19. Chapter 19: Game Programming Design Patterns – Starting the Space Invaders ++ Game 20. Chapter 20: Game Objects and Components 21. Chapter 21: File I/O and the Game Object Factory 22. Chapter 22: Using Game Objects and Building a Game 23. Chapter 23: Before You Go... 24. Other Books You May Enjoy

Chapter 15: Advanced OOP – Inheritance and Polymorphism

In this chapter, we will further extend our knowledge of OOP by looking at the slightly more advanced concepts of inheritance and polymorphism. We will then be able to use this new knowledge to implement the star characters of our game, Thomas and Bob. Here is what we will cover in this chapter:

  • Learn how to extend and modify a class using inheritance
  • Treat an object of a class as if it is more than one type of class by using polymorphism
  • Learn about abstract classes and how designing classes that are never instantiated can actually be useful
  • Build an abstract PlayableCharacter class
  • Put inheritance to work with the Thomas and Bob classes
  • Add Thomas and Bob to the game project

Inheritance

We have already seen how we can use other people's hard work by instantiating objects from the classes of the SFML library. But this whole OOP thing goes even further than that.

What if there is a class that has loads of useful functionality in it, but is not quite what we want? In this situation, we can inherit from the other class. Just like it sounds, inheritance means we can harness all the features and benefits of other people's classes, including the encapsulation, while further refining or extending the code specifically to our situation. In this project, we will inherit from and extend some SFML classes; we will also do so with our own classes.

Let's look at some code that uses inheritance.

Extending a class

With all this in mind, let's look at an example class and see how we can extend it, just to see the syntax and as a first step.

First, we define a class to inherit from. This is no different from how we created any of our other...

Polymorphism

Polymorphism allows us to write code that is less dependent on the types we are trying to manipulate. This can make our code clearer and more efficient. Polymorphism means many forms. If the objects that we code can be more than one type of thing, then we can take advantage of this.

Important note

But what does polymorphism mean to us? Boiled down to its simplest definition, polymorphism means the following: any sub-class can be used as part of the code that uses the super-class. This means we can write code that is simpler and easier to understand and also easier to modify or change. Also, we can write code for the super-class and rely on the fact that no matter how many times it is sub-classed, within certain parameters, the code will still work.

Let's discuss an example.

Suppose we want to use polymorphism to help write a zoo management game where we must feed and tend to the needs of animals. We will probably want to have a function such as feed....

Abstract classes – virtual and pure virtual functions

An abstract class is a class that cannot be instantiated and therefore cannot be made into an object.

Tip

Some terminology we might like to learn about here is concrete class. A concrete class is any class that isn't abstract. In other words, all the classes we have written so far have been concrete classes and can be instantiated into usable objects.

So, it's code that will never be used, then? But that's like paying an architect to design your home and then never building it!

If we, or the designer of a class, wants to force its users to inherit it before using their class, they can make a class abstract. If this happens, we cannot make an object from it; therefore, we must inherit from it first and make an object from the sub-class.

To do so, we can make a function pure virtual and not provide any definition. Then, that function must be overridden (rewritten) in any class that inherits from...

Building the PlayableCharacter class

Now that we know the basics of inheritance, polymorphism, and pure virtual functions, we will put them to use. We will build a PlayableCharacter class that has most of the functionality that any character from our game is going to need. It will have one pure virtual function, known as handleInput. The handleInput function will need to be quite different in the sub-classes, so this makes sense.

As PlayableCharacter will have a pure virtual function, it will be an abstract class and no objects of it will be possible. We will then build the Thomas and Bob classes, which will inherit from PlayableCharacter, implement the definition of the pure virtual function, and allow us to instantiate Bob and Thomas objects in our game. It will not be possible to instantiate a PlayableCharacter instance directly, but we wouldn't want to because it is too abstract anyway.

Coding PlayableCharacter.h

As usual when creating a class, we will start off...

Building the Thomas and Bob classes

Now, we get to use inheritance for real. We will build a class for Thomas and a class for Bob. They will both inherit from the PlayableCharacter class we just coded. They will then have all the functionality of the PlayableCharacter class, including direct access to its protected variables. We will also add the definition for the pure virtual function, handleInput. You will notice that the handleInput functions for Thomas and Bob will be different.

Coding Thomas.h

Right-click Header Files in the Solution Explorer and select Add | New Item.... In the Add New Item window, highlight (by left-clicking) Header File (.h) and then, in the Name field, type Thomas.h. Finally, click the Add button. We are now ready to code the header file for the Thomas class.

Add the following code to the Thomas.h class:

#pragma once
#include "PlayableCharacter.h"
class Thomas : public PlayableCharacter
{
public:
    // A constructor...

Updating the game engine to use Thomas and Bob

In order to be able to run the game and see our new characters, we have to declare instances of them, call their spawn functions, update them each frame, and draw them each frame. Let's do that now.

Updating Engine.h to add an instance of Bob and Thomas

Open up the Engine.h file and add the following highlighted lines of code:

#pragma once
#include <SFML/Graphics.hpp>
#include "TextureHolder.h"
#include "Thomas.h"
#include "Bob.h"
using namespace sf;
class Engine
{
private:
    // The texture holder
    TextureHolder th;
    // Thomas and his friend, Bob
    Thomas m_Thomas;
    Bob m_Bob;
    const int TILE_SIZE = 50;
    const int VERTS_IN_QUAD = 4;
    ...
    ...

Now, we have an instance of both Thomas...

Summary

In this chapter, we learned about some new C++ concepts, such as inheritance, which allows us to extend a class and gain all its functionality. We also learned that we can declare variables as protected and that this will give the child class access to them, but they will still be encapsulated (hidden) from all other code. We also used pure virtual functions, which make a class abstract, meaning that the class cannot be instantiated and must therefore be inherited from/extended. We were also introduced to the concept of polymorphism, but will need to wait until the next chapter to use it in our game.

In the next chapter, we will add some major functionality to the game. By the end of the next chapter, Thomas and Bob will be walking, jumping, and falling. They will even be able to jump on each other's heads, as well as exploring some level designs that have been loaded from a text file.

FAQ

Q) We learned about Polymorphism, but why didn't I notice anything polymorphic in the game code so far?

A) We will see polymorphism in action in the next chapter when we write a function that takes PlayerCharacter as a parameter. We will see how we can pass both Bob and Thomas to this new function. It will work the same with both of them.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Beginning C++ Game Programming. - Second Edition
Published in: Oct 2019 Publisher: Packt ISBN-13: 9781838648572
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}