Object Oriented Programming OOP, is how most programming is done these days. While it is possible to code a game without using it and many games in the past were, even the most simple game projects will benefit greatly from using OOP. So what exactly is it and how do we get started using OOP? After you complete this short tutorial you will be ready to make the first fully working C++ game from the SFML game projects section.
[widgets_on_pages id=”udemy_advert_cpp_1″][widgets_on_pages id=”udemy_code_details”]

What is OOP?

OOP is a way of programming that involves breaking game’s constituent parts into pieces that are more real-world and logical than the data types that they comprise. Each piece is self-contained yet potentially reusable by other programs while working together as a whole with all the other pieces. These pieces of code are the objects of object-oriented programming. In C++ we plan an object by coding a class. A class can be thought of as the blueprint of an object.

We implement an object of a class. This is called an instance of a class. Think about a house blueprint? You can’t live in it, but you can build a house from it, you build an instance of it. However, OOP is more than this. It is also a methodology or model that defines best practices including these core aims:

  1. Encapsulation: This means keeping the internal workings of your code safe from interference from the programs that use it. Allowing only the variables and functions you choose to be accessed. This means your code can always be updated, extended or improved without affecting the programs that use it, as long as the exposed parts are still accessed in the same way.
  2. Inheritance: Just like it sounds, inheritance means we can harness all the features and benefits of other people’s classes, including encapsulation and polymorphism while refining their code specifically to our situation. We will do this in every single game project we make with both our own classes and the classes provided by the C++ language.
  3. Polymorphism: This allows us to write code that is less dependent on the types we are trying to manipulate, making our code clearer and more efficient. Some examples later in our game projects and in the final tutorial of this series will make things a bit clearer.

C++ was designed by Bjarne Stroustrup to improve upon the then dominant language of the day, C. Crudely put you could describe C++ as C with classes.

We will see how to use some classes in the remaining tutorials in this series and we will use loads of other people’s classes too when we make our games- it is really easy! In particular, we will be using the classes of the SFML library.

We also need to make our own classes, however (Paddles, balls, spaceships, aliens etc) so for the rest of this tutorial we will concentrate on how we do that.

Building our own classes

[widgets_on_pages id=”bcgp_cfgp_gpp”]

A class is some code that can contain functions, variables, loops etc. In fact, C++ code we have learnt about so far can be part of a class. Typically we define a new class in its own code file and then include that file in our main c++ source file. Forget about how we might do this for now because this is more easily demonstrated with a real example rather than explained in a tutorial like this. Let’s concentrate on the code itself to write and then use a class.

Once we have written a class we can use it to make as many objects from it as we need. Remember, the class is the blueprint and we make objects based on the blueprint. The house isn’t the blueprint just as the object isn’t the class; it is an object made from the class. Let’s take a look.


class Paddle
{
   public:
      int length = 100;      // Length of a pong paddle
      int height = 10;      // Height of a pong paddle

      int xPosition;      // Location on x axis
      int yPosition;      // Location on y axis

      void movePaddleRight()
      {
		// Move the paddle a pixel to the right
        xPosition ++;

		// Back to main game code
		return;
      }

	  void movePaddleLeft()
      {
		// Move the paddle a pixel to the right
        xPosition --;

		// Back to main game code
        return;
      }
};

Above is a class definition for a class called Paddle. Within the Paddle class are four variables, an int variable called length, a int variable called height, an int variable called xPosition and a int variable called yPosition . There is also two functions called movePaddleRight and movePaddleLeft. The functions have no parameters and a void return type but class functions can be of any shape or size that we discussed in the tutorial Organizing our code with functions. The functions simply add one or take one away from the xPosition variable. This code is slightly hypothetical but hopefully you can imagine how calling these functions would have the effect of moving a pong paddle left and right.

The functions that belong to the class act upon the variables of the class. We call variables that are part of a class, members. Remember this is just a class, not an object. It is a blueprint for a Pong paddle, not an actual paddle. This is how we make an object of type Paddle from our Paddle class.

Paddle myPaddle;

The code, Paddle myPaddle declares a new object variable of type Paddle called myPaddle.

This is how we would assign values to and use the member variables inside the Paddle class.

myPaddle.xPosition = 100;
myPaddle.yPosition = 800;

// Notice that we use the object name myPaddle.
// Not the class name Paddle.
// We didn't do this:
// Paddle.xPosition = 100; ERROR!

Above, the dot operator “ .” is used to access the member variables of the class. This is also how we use the functions; by using the object’s name followed by the dot operator.

// Player has pressed the right arrow key
myPaddle.movePaddleRight();

We can make as many Paddle objects as we like.

Paddle myPaddle2;
myPaddle2.xPosition = 300;
myPaddle2.yPosition = 100;

// Add as many paddles as you like

It is important to realize that myPaddle2 is a totally separate object with its very own variables. Just because your neighbor’s house might have been built from the same blueprint as your own, doesn’t mean that you live in it.

Constructing our objects in the constructor

Another concept we need to go over before we can get on and do something practical with what we have just learned. A constructor is a special function which is executed/run at the time the object is created. When we used the code Paddle myPaddle this special function provided for us, called the constructor runs. As we almost always will want to set our objects up at the same time as we create them we can provide an overridden constructor that takes parameters, just like the C++ functions we learned about previously. Here is a hypothetical constructor that might be useful for positioning a paddle on the screen.

Paddle(float startX, float startY)
{
	xPosition = startX;
	yPosition = startY;
}

Notice that the constructor is just the same as a function but its name is the same name as the class. Now we can use this constructor when we create our paddle like this:

// Place our paddle at the center bottom of a 1920 x 1080 screen
Paddle myPaddle(960, 1070);

It is worth mentioning that when we actually make a game the code will look slightly different to this. The code we have seen is pure C++. When we make games we will customize it slightly to suit the library/engine we are using. One more quick topic then we will make a game.

Access modifiers

[widgets_on_pages id=”udemy_advert_cpp_2″][widgets_on_pages id=”udemy_code_details”]
If you were wondering what that public keyword was when we defined our Paddle class, all will be made clear now. All of our class member variables, functions and the classes themselves can be given different access modifiers. We use access modifiers to specify which other code can access different parts (variables, functions, classes) of our code. This topic on its own is a fairly enormous one but we don’t have to master it to start making games. When we make and use classes during our game projects I will point out when and why we use a particular access modifier.

The two main access modifiers are public and private. Just know that public functions and variables are almost completely accessible and private are generally hidden within the class itself. This allows us to write code that uses variables that can only be manipulated by the code within the class itself. For example we wouldn’t want a hypothetical SpaceInvader class altering our Paddle position!

What was that you just said about classes?

It doesn’t really matter if you haven’t understood everything and you probably have a mountain of questions. OOP is a vast topic and it would take multiple books just to do this one topic justice. All we want to achieve with this tutorial is to get enough information to code a real C++ game. We can then learn more as we progress. As long as you understand that we can design a class which acts like a blueprint and that we can create objects from that blueprint that actually use that code then you know enough to proceed. I will fully explain what is happening when we design some classes and create objects from them.

So we know that not only can we design and use our own classes but we can also use, without worrying about the internal workings, other people’s classes. It just so happens that SFML is stuffed full of classes (and functions) that cover just about everything we will ever need to make a 2d game. So let’s do that now and code a pong game with c++