Navigation: Introduction to Programming

Tutorial 3 - The C++ Language


Overview

In this tutorial I will explain the different parts of a c++ application. We will explore c++ syntax, responding to user input, object-oriented concepts and data encapsulation.

First things First

Every c++ application is made up of headers and cpp files. Headers and cpp files are both ordinary text files but they have the extension .h, .cpp or .hpp. Like a text file can have the extension .txt or an image might have .png for png images and .jpg or .jpeg for jpeg images.
Open up the visual studio project you created in the last tutorial. You can do this by going to File > Open > Project in Visual Studio.

Notice to the left of the screen in Solution Explorer you will see Header Files, Resource Files and Source Files(See Figure 3.). Any code you write in c++ is called source code or any code you write in any language is called source code in fact. I tend to think of .cpp files as source code however and .h files as headers but they are both technically source code. It helps to distinguish headers from source because the bulk of code that you will write will be contained in the cpp files. Headers just provide an outline or skeleton to the code.


Figure 3.

Basically what you need to understand is that headers should contain declarations and cpp files should contain definitions. This will become more clear when I describe the c++ syntax and object-oriented programming.

We have already created a .cpp file, main.cpp. To create a header file right-click Header Files Add > New Item, Select Header File (.h), enter a name for the file and click Add.

Syntax

Syntax is the rules that make up a language. English for example has clearly defined rules: put a dot at the end of a sentence, start with a capital letter. Syntax lets a compiler translate code and process it into low-level binary format that the computer understands. C++ has it's own syntax and most programming languages have almost exactly the same syntax.

To give you an example of c++ syntax consider the following:
int i = 0;
int x = 5;
This defines two integers i and x. By definition an integer is any whole number but because computers have limited memory these integers are actually in the range of −2,147,483,648 to 2,147,483,647. Here we set i to 0 and x to 5. The semi-colon denotes the end of a statement.

Let's break this up into the syntactic components, we have a few things going on here:
int Means integer, it is also called a data type
i or x A variable - it's value can vary
= the equals operator, a single = is also called an assignment operator and a double == is called the comparison operator
0 or 5 A number
; End of statement

Comments

//This is a comment

/*
This is a multi-line comment.
These are usually used to provide documentation about 
what your code does.
*/

Comments don't do anything but they are very useful. By adding comments to your code you can give yourself reminders about how parts of your code operate or you can use them to help other programmers understand code you have written.

Operators

= Assignment operator; it assigns a value to a variable
== Comparison operator; it compares two values
+ Addition operator; it adds a value on the right to a value on the left
- Subtraction operator; it subtracts a value on the right from a value on the left
* Multiplication operator; multiplies a variable by a value
/ Division operator; divides a variable by a value
++ Increments a variable by 1
-- Decrements a variable by 1
! "Not" symbol; it turns true into false and false into true e.g. bool b = !true;
!= "Not equals" operator; returns true if two values are not equal e.g. 1 != 2
+= e.g. x += 2 is equivelant to x = x + 2
-= e.g. x -= 6 is equivelant to x = x - 6

Switch Statements

int value = 2;

switch(value)
{
case 1:
  //Do something if value is 1
  break;
case 2:
  //Do something if value is 2
  break;
case 5:
  //Do something if value is 5
  break;
default:
  //Do something for every other value other than 1, 2 and 5
  break;
}

Switch statements compare the value of a number or variable with one of the case labels. In the example above if value equals 1, the code after case 1: and before break; is executed. If the value is 5, the code after case 5: and before break; is executed.

Since the value is 2, //Do something if value is 2, is executed.

Functions

Functions are a fundamental component of computer programming.
Look at the example below and I will describe how it works to give you an idea of how to use functions and what they can do.
The following program will compile and run. You will encounter functions all the time while writing a game and you will no doubt find it useful to write your own.

main.cpp
int AddTwoNumbers(int n1, int n2)
{
	return n1 + n2;
}

int main()
{
	int x = AddTwoNumbers(5, 6);

	return 0;
}

Functions Explained:
Every function has a return value, one of the built-in data types, int, float or double for example, or a data type you have created yourself. In the case of the AddTwoNumbers() function we have made the return value int by putting int in front of the function name. If you look at the main() function you will notice the return value of AddTwoNumbers() is assigned to the variable x - 11 is assigned to x.

main() is a special function because any typical console application will call the main() function and execute it first when you run the .exe. Because it is called main() your compiler will make it the "entry point" of your application and execute it first. In a windows application however, not a console application the entry point is called WinMain(). You need to know this otherwise you won't know why main() is executed and not some other function.

Parameters are the things we pass to a function, in this case 5 and 6 are the parameters to the function AddTwoNumbers(). n1 becomes the value 5 and n2 becomes the value 6. In this way we can use the name n1 and n2 in the function code contained within the AddTwoNumbers() curly brackets to deal with parameters of different values. n1 and n2 are added together as you can see above and the sum becomes the return value. The return value is then assigned to the variable x by calling the function. You call a function by typing it's name and round brackets and passing parameters to it.

Functions are very useful. You will begin to understand the need for them the more you program. One use for functions is to have code that you might use over and over in different areas of your program, by using a function you don't have to write the same code twice if it can be turned into a function and essentially this will add to the clarity of your code because you can call the function any time you want to use that code.

Parameters can be passed by value or they can be passed by reference. By value for example is where the value of a parameter such as 5 or 6 in the case above is actually copied to a local function parameter, in the case above the value 5 is actually copied(assigned) to the local function variable n1 and 6 is assigned to the local function variable n2. Local means that n1 and n2 can't be used outside of the function, they are local only to the function AddTwoNumbers().

Passing parameters by reference requires a bit more understanding. I won't go into the details of memory addresses here, as long as you know how to use parameters passed by reference you should be ok. Passing parameters by reference allows you to access the members of an object(a complex data type) passed to a function from within the function without actually copying the whole object and all it's members every time it is passed as a parameter. Instead, if the object is quite big it might not be practical or efficient to copy it I mean pass it as a parameter by value if the pass occurs frequently. So passing it by reference could be preferable.

Example of passing a custom data type, MyObject, by reference:

(More on custom data types Later.)
struct MyObject
{
//Declare member variables.
float x;
float y;

	//This function is called a constructor because it 
	//constructs the object.  You can define the 
	//behaviour of it yourself.
	//Constructors always have the same name as 
	//the class or struct.
	MyObject()
	{
		x = 0.0f;
		y = 0.0f;
	}
};

void MyFunction(MyObject* o)
{
	//Access the members of o.

	//Add x and y together to get a result.
	float result = o->x + o->y;
}

int main()
{
	//Create an instance of MyObject.
	MyObject o1;

	//Pass the instance to the function by reference.
	MyFunction(&o1);

	return 0;
}

void simply means the function has no return value. float is a decimal number with a point as opposed to integer. Putting an f after a number ensures it is a float and not a double. A double is also a decimal number but it takes up more memory than a float so it's usually good practice to use the f notation when working with floats.

Loops

while(x < 17)
{
	//Do Something.

	//Increase x by 1.
	x++;
}

Loops come in a number of forms. While loops, For loops, do{ }While() loops.

for(int x=0; x<17; x++)
{
	//Do Something.
}

In English, this reads "for x equals 0, x below 17, x plus plus". In the for loop above x starts at zero and is incremented by 1 each cycle of the loop. x will be zero over the first cycle. A cycle or execution of the code within a loop is also called an iteration. In the for loop above there will be 17 iterations. When x=17 the loop will end and so if you use x in the loop code it will be from 0 to 16. As soon as x reaches 17, once the current cycle has finished, the code after the loop will be executed. This is because the value of x is checked at the beginning of the loop. The condition is that x must be below 17, and if it is not, the loop will end.

bool end_loop = false; //bool means boolean.
		       //boolean can be true or false.

//Loop infinitely
while(true)
{
	//Do Something.

	if(end_loop == true){
		//Exit the loop here.
		//Continue executing code after
		//the while loop.
		break;
	}
}

bool loop_ended = true; //This code will be executed
			//if you break the while loop.

break; can be used to terminate any kind of loop at any point in the loop. In the example above if end_loop is set to true somewhow then break; will happen as you can see. end_loop is just an ordinary bool variable, it's value can be true or false. You could name it something else if you choose.

Input / Output

I am going to cover basic input and output here to make it easier for you to understand some of the future concepts being tought. Having an interactive program is far more interesting than having a program that runs and shuts down straight away. Input here refers to keyboard presses and output refers to displaying text in the console window. You are not expected to understand the following code completely. I will explain #include and namespaces later. All you should do at this point is examine the code executed for each key that is pressed in main.cpp below. All you need to know about cout is that if you type cout << "something"; then "something" will be displayed in the black console window.

Because later on we will be focusing primarily on creating windowed or graphic applications I do not want you to spend time learning all about console applications and that is why I say All you need to know about cout is that if you type cout << "something"; then "something" will be displayed in the black console window. To use cout however you do need to put #include <iostream> using namespace std; at the top of the file where you use cout.

The following program detects if the user presses the Left, Right, Up or Down arrow keys on the keyboard. If Left is pressed, then "Left" is displayed in the console window and if Right is pressed, then "Right" is displayed in the console window.

Try it out for yourself.

Press Escape to exit the program.

There are 3 files to this program:
  • KeyboardInput.h
  • KeyboardInput.cpp
  • main.cpp
Make sure you include them in your project, remember I showed you how to add headers and source code. Note: The only file you need to look at here is main.cpp.

Add and replace the code in your current project with the following files:

KeyboardInput.h
/*
This header file declares the KeyboardInput class that
will be used to handle keyboard presses.

Author: Douglas MacLeod
Date: 2015
*/

class KeyboardInput
{
public:
	KeyboardInput();

	bool LeftKeyPress();
	bool RightKeyPress();
	bool UpKeyPress();
	bool DownKeyPress();
	bool EscapeKeyPress();

private:
	bool m_bLeftKeyDown;
	bool m_bRightKeyDown;
	bool m_bUpKeyDown;
	bool m_bDownKeyDown;
	bool m_bEscapeKeyDown;
};


KeyboardInput.cpp
/*
This source file defines the implementation of the 
KeyboardInput class.

Author: Douglas MacLeod
Date: 2015
*/

#include "KeyboardInput.h"
#include <windows.h>

KeyboardInput::KeyboardInput()
{
	m_bLeftKeyDown = false;
	m_bRightKeyDown = false;
	m_bUpKeyDown = false;
	m_bDownKeyDown = false;
	m_bEscapeKeyDown = false;
}

//Left Key.
bool KeyboardInput::LeftKeyPress(){
	//Is key down?
	if (GetKeyState(VK_LEFT) & 0x8000){
		//Yes.
		if(m_bLeftKeyDown == false){
			m_bLeftKeyDown = true;
			return true;
		}
	}
	else if(m_bLeftKeyDown == true){
		//Key is released.
		m_bLeftKeyDown = false;
	}

	return false;
}

//Right Key.
bool KeyboardInput::RightKeyPress(){
	//Is key down?
	if (GetKeyState(VK_RIGHT) & 0x8000){
		//Yes.
		if(m_bRightKeyDown == false){
			m_bRightKeyDown = true;
			return true;
		}
	}
	else if(m_bRightKeyDown == true){
		//Key is released.
		m_bRightKeyDown = false;
	}

	return false;
}

//Up Key.
bool KeyboardInput::UpKeyPress(){
	//Is key down?
	if (GetKeyState(VK_UP) & 0x8000){
		//Yes.
		if(m_bUpKeyDown == false){
			m_bUpKeyDown = true;
			return true;
		}
	}
	else if(m_bUpKeyDown == true){
		//Key is released.
		m_bUpKeyDown = false;
	}

	return false;
}

//Down Key.
bool KeyboardInput::DownKeyPress(){
	//Is key down?
	if (GetKeyState(VK_DOWN) & 0x8000){
		//Yes.
		if(m_bDownKeyDown == false){
			m_bDownKeyDown = true;
			return true;
		}
	}
	else if(m_bDownKeyDown == true){
		//Key is released.
		m_bDownKeyDown = false;
	}

	return false;
}

//Escape Key.
bool KeyboardInput::EscapeKeyPress(){
	//Is key down?
	if (GetKeyState(VK_ESCAPE) & 0x8000){
		//Yes.
		if(m_bEscapeKeyDown == false){
			m_bEscapeKeyDown = true;
			return true;
		}
	}
	else if(m_bEscapeKeyDown == true){
		//Key is released.
		m_bEscapeKeyDown = false;
	}

	return false;
}


main.cpp
#include "KeyboardInput.h"
#include <iostream>
using namespace std;

int main()
{
	KeyboardInput keyboard;

	//Program Loop.
	while(true)
	{
		if (keyboard.LeftKeyPress())
		{
			// Left key has been pressed.
			cout << "Left" << "\n";
		}

		if (keyboard.RightKeyPress())
		{
			// Right key has been pressed.
			cout << "Right" << "\n";
		}

		if (keyboard.UpKeyPress())
		{
			// Up key has been pressed.
			cout << "Up" << "\n";
		}

		if (keyboard.DownKeyPress())
		{
			// Down key has been pressed.
			cout << "Down" << "\n";
		}

		if (keyboard.EscapeKeyPress())
		{
			// Escape key has been pressed.
			// End loop.
			break;
		}
	}

	//Program Loop has Ended.

	//Exit Program.
	return 0;
}
As you can see the program loops forever checking for key presses until you press Escape key, the loop stops and the program exits. keyboard. (with a dot) will make sense when you understand object-oriented programming. All I want you to know here is that you can put whatever code you want to execute between the curly brackets corresponding to each of the arrow keys when one of the arrow keys is pressed. In this way you can make your program respond to input from the user.

Object-Oriented Programming

Now I'm going to jump right into the fun stuff, objects and instances.
Now that you have a program that can respond to user input I think it's a good time to explain what objects and instances of objects are and how you can use them.

You have already come across one object, KeyboardInput but you may have no idea how it works.

In this section of the tutorial I want to explain how you can define your own objects in c++ and how you can create instances of those objects.

Let's consider an every day object, a Car. A car is an object and when we talk about a car we usually share a similar idea: Something with four wheels, an engine, a colour and can move at a speed in some direction. There are many different types of cars, for example Honda, Ford, Mazda. In c++ we call these types objects or data types. A ball is an object, a wizard in a computer game is an object, an aeroplane is an object. Now imagine you have two cars next to each other, a red Honda and a black Honda. They are both Hondas but they have different properties, one is red and the other one is black. In a factory that manufactures Hondas the machines that actually build the cars are programmed to know what a Honda is, but every car that the machine actually builds is different, it's colour might be red or it's colour might be black, one might drive at 20mph while the other at 50mph. They are both Hondas. We call each of the hondas an instance of a Honda and we call each car an instance of a Car. In c++ Honda is the object for example and each different Honda is called an instance of a Honda.

So how do we define an object in code?

And how do we create instances of those objects?

Usually we describe an object in a header file .h (See Headers below) and we describe the behaviour of an object in a .cpp file. The description of the object is called a declaration and it's behaviour or implementation is called a definition.

An object can have variables, for example colour, speed, and objects may also have functions(also called methods.). A method of a car might be DriveForward() or Reverse(). When you create an instance of an object, you can call the methods of that object to interact with that instance, for example if you had an instance of a car, let's call it car1, you could make the car drive by typing car1.DriveForward(). If you have created a Monster object and it has a method SwingAxe(), then you can create an instance of the monster monster1. You could make the monster swing his axe if it comes close to your character for example monster1.SwingAxe().

To create an object in c++, you use the word class or struct, depending on the kind of object you need. The difference is that a class can have public and private members while all the members of a struct(structure) are public, more on this later. Let's take a simple example of declaring a Dog object. Every dog can typically bark so we will declare one method Bark() and a method Eat(). To make an instance of our dog bark we could do something like dog1.Bark() every time we want to make dog1 bark. In our Dog object, we will declare a member variable hungry that can be true or false; If the dog is hungry then hungry is true, otherwise if the dog is not hungry, hungry will be false. We will make every instance of our dog hungry at first, when the dog is created, and then when it eats we will set hungry to false because the dog is no longer hungry. As I mentioned, we declare objects in a header file and we define the behaviour of those objects in a .cpp file.

Here is how we could declare a simple dog:
Dog.h

class Dog
{
public:
	Dog();
	~Dog();

	void Bark();
	void Eat();

private:
	bool hungry;
};


Above is a class declaration. You must put a semi-colon at the end of every class declaration after the last curly bracket; If you don't put a semi-colon at the end, you will get a compile error. At the moment we have not defined any dog behaviour. We have only declared the methods, Bark() and Eat() and a member variable hungry. Because Bark() and Eat() have no implementation you will get a compiler error if you try to create an instance of Dog and compile. In c++ it is said to be illegal to write code that isn't directly part of the c++ language or that the compiler doesn't like in other words. So it is said to be illegal to create an instance of an object that doesn't have an implementation.

Now we have declared the Dog object let's examine it.

Every object(class or struct) that you define in c++ has a constructor and a destructor. Here the constructor is Dog() and the destructor is ~Dog(). The constructor and destructor are both methods like other methods, they can be called in the same way as another class method, for example dog3.Dog(). You do not have to declare these methods manually because they will always exist for every class or struct. You do however have to implement them manually if you declare them manually as with other methods. The reason you might type them manually is if you want to define the behaviour yourself when an instance of an object is created or destroyed. When you create an instance of an object, it's constructor is always called and when it is destroyed, for example when the game terminates, it's destructor is always called. Because they have the same name as the class itself, this is why they are called when an instance is created or when an instance is destroyed; it is part of the c++ language to call a constructor or destructor on creation or destruction.

Look at the dog class above, it has a constructor Dog(), a destructor ~Dog() and two methods Bark() and Eat(). If you remember from the section on functions, every function has a return value e.g. int, float, bool etc. The only functions that don't have return values are constructors and destructors. Although void doesn't actually return anything, it must be the return value when you don't want to return anything for functions other than constructors and destructors. void is the return value of Bark() and void is the return value of Eat().

Now let's implement the Dog class and give the dog some behaviour.
Dog.cpp

#include "Dog.h"

Dog::Dog()
{
	//Make the dog hungry.
	hungry = true;
}

Dog::~Dog()
{
}

void Dog::Bark()
{
	//Play sound.
}

void Dog::Eat()
{
	hungry = false;
}

What's going on here?

This(Dog.cpp) is what the implementation of a class looks like, a simple class. The double colon :: is called the scope resolution operator. What it does is it basically accesses members or allows members such as functions and variables of some scope to be accessed. In the case above the scope is Dog where :: is used. Scope means the context or place where something resides. For example, the scope of a file means all the text in that file and the scope of a class means everything contained in the curly brackets of the class declaration. Here the hungry variable is within the scope of the Dog class and we access the members of Dog with ::.
main() for example is in the scope of the main.cpp file and it is not in the scope of Dog. You can use variables declared in a class, such as hungry, in any of the class's member functions by typing it's name because it is in the same scope as the function; the scope here being Dog. For example we have used hungry in the class constructor and we have used hungry in the function Dog::Eat(); This is allowed because hungry is in the same scope as the functions themselves. If you want to use a class variable in another scope it must be public and you can type instance_name.variable_name to use it like any other variable. The :: double colon only applies to objects and namespaces, more on namespaces later, for example Dog::Eat() allows us to "look-up" the function Eat() and implement it where as a single . dot is used to call functions on instances, dog1.Eat(), dog2.Eat() for example. This is how the double colon differs from a single dot.

If you include a class such as Dog with #include "Dog.h" in a .cpp file you can then access the members of Dog by using the scope operator. See above we are accessing the members of Dog with the :: operator, Dog::Bark(), Dog::Eat(). If you do not include Dog.h with #include "Dog.h" in a .cpp file, that .cpp file will not know about the Dog class.

Basically headers .h files are where we declare objects, such as Dog; it's functions and variables. And then .cpp files are where we implement the behaviour of those objects and use them. The #include at the top of a .cpp file "includes" a header, the code it contains into the .cpp file. It is like copying all the code in the header to the place where you put the #include "headername.h". You can include any header in any .cpp file and by including a header, it allows you to use the classes declared in that header in a .cpp file.

You're probably wondering how you create an instance of an object at this point. It's quite simple. The following code creates two dogs. It makes dog1 bark.
main.cpp

#include "Dog.h"

int main()
{
	Dog dog1;
	Dog dog2;

	dog1.Bark();

	return 0;
}

Data Encapsulation

Data encapsulation is a technique used to protect or maintain data integrity from mis-use of variables and functions through-out a program either from yourself, or from someone else using your code. It protects the data stored throughout a program from being modified where it shouldn't be. You might forget for example that you didn't want a variable you created to be modified outside a class because some part of your program depends upon the integrity of the variable. With data encapsulation you can prevent the variable from being modified outside of a class by making it private. Let's look at the Dog class again:
Dog.h

class Dog
{
public:
	Dog();
	~Dog();

	void Bark();
	void Eat();

private:
	bool hungry;
};
Here I have used data encapsulation to make Bark() and Eat() public and I have made hungry private. This is because it takes time for a dog to become hungry, it doesn't just become hungry at any time, so we shouldn't be allowed to make the dog hungry at any part of the program outside of the dog. Instead it's digestive system should control whether it is hungry or not and this will be controlled by the dog itself. A dog can bark and eat however at any time so I have made these functions public. By calling Bark() or Eat() doesn't change any data to something it shouldn't be so it is safe to make these functions public. Public functions and variables can be accessed and used in any scope where they are included. If you have a dog instance called dog1 then you can't use dog1.hungry outside the Dog scope because it is private; The compiler won't let you and will tell you that hungry is private if you try to compile the program.

There are 3 access modifiers in C++:
  • public
  • protected
  • private

Public Members
public members can be accessed in any scope where you have included the class. For example, look at Dog.h above; it has 4 public functions Dog(), ~Dog(), Bark() and Eat(). You can call these on any instance of Dog, like dog1.Bark(), in any scope where you have the instance, such as main().

Protected Members
Protected members are only accessible by the class they are defined in and also by subclasses of that class. They are not accessible outside of subclasses and the class they are defined in(subclasses will be covered in the next tutorial, Tutorial 4).

Private Members
Private members can only be accessed by the class they are defined in or by the functions of the class they are defined in. In the example above, you can access hungry within the Bark() function or the Eat() function because these are part of the class. private members are inherited by subclasses but not accessible by them besides the inherited functions(subclasses will be covered in the next tutorial, Tutorial 4).

An Interactive Program

Finally, to conclude this tutorial, I will provide an interactive example of having a Car object respond to user input and a small section on headers.

Use the Left arrow key to steer the car left.
Use the Right arrow key to steer the car right.
Use the Up arrow key to drive faster.
Press Escape to exit the program

Take a look at the program code below, all the files you need for this program can be found on this web page. There are 5 files:
  • KeyboardInput.h
  • KeyboardInput.cpp
  • Car.h
  • Car.cpp
  • main.cpp
To save clutter, KeyboardInput.h and KeyboardInput.cpp can be found above on this web page. Copy the code into your own project.

For the remaining files Car.h, Car.cpp and main.cpp, you can find these below. Examine the code and try to understand it. #pragma once stops the header .h being included more than once, as it is not allowed to have a class declaration twice, so we want to make sure classes in a header are declared only once - at the first occurence of #include "Car.h". If we had #include "Car.h" twice, then #pragma once stops class Car being declared twice and this allows you to include Car.h in multiple files without redeclaration problems.

The other thing that needs explaining is the keyword this. If you look at the constructor for Car, you can see this is used. Sometimes parameters have the same name as variables you have defined in a class. By using this-> we can distinguish between a local parameter variable and a variable that is part of the class. As you can see the member variable type is set to the parameter variable type and the member variable colour is set to the parameter variable colour. this is actually a pointer(Pointers are covered in Tutorial 4).

Finally, some headers that you include have angled brackets around them, <string> These are headers that are part of the standard set of headers that are part of the standard library for c++. You will be able to use any of these standard C++ headers if you downloaded Visual Studio.

(Namespaces are covered in the next tutorial)

"\n" means end line.
Car.h

#pragma once

#include <string>

using namespace std;

class Car
{
public:
	Car(string type, string colour, float horsepower);
	~Car();

	void SteerLeft();
	void SteerRight();
	void DriveFaster();

private:
	string type;
	string colour;
	float horsepower;
	float speed;
	float direction;
};
Car.cpp

#include "Car.h"
#include <iostream>

using namespace std;

Car::Car(string type, string colour, float horsepower)
{
	this->type = type;
	this->colour = colour;
	this->horsepower = horsepower;

	speed = 0;
	direction = 0; //0-360 degrees
}

Car::~Car()
{
	//This function is called the Destructor.
	//It is called when the car is destroyed.
}

void Car::SteerLeft()
{
	direction = -45.0f;

	cout << "Steering Left" << "\n";
}

void Car::SteerRight()
{
	direction = 45.0f;

	cout << "Steering Right" << "\n";
}

void Car::DriveFaster()
{
	//set speed to speed + 1
	speed += 1.0f;

	cout << "Driving at " << speed << "mph" << "\n";
}

main.cpp

#include "KeyboardInput.h"
#include "Car.h"

int main()
{
	KeyboardInput keyboard;

	Car my_ferrari("Ferrari", "red", 660);

	//Program Loop.
	while(true)
	{
		if(keyboard.LeftKeyPress()){
			my_ferrari.SteerLeft();
		}

		if(keyboard.RightKeyPress()){
			my_ferrari.SteerRight();
		}

		if(keyboard.UpKeyPress()){
			my_ferrari.DriveFaster();
		}

		if(keyboard.EscapeKeyPress()){
			//End loop.
			break;
		}
	}

	//Exit Program.
	return 0;
}

Headers

Basically a header contains a description of one or more objects. It contains the functions and member variables of these objects but not how these functions behave. A header does not contain the implementation of these objects functions in other words. You include a header at the top of any file where you need to use the objects declared in the header with #include "headername.h"

Both headers .h files and source code .cpp files both contain c++ code but they are different from .cpp files. Headers .h files should only contain declarations of objects and .cpp files can contain both declarations and definitions. There is a fine distinction between a declaration, sometimes called a prototype, and a definition (See Object-Oriented Programming). But there is a good reason why headers should not contain implementations besides it being good coding practice. It is to do with the way a c++ compiler builds and generates your standalone executable. A compiler will generate an .obj file for each of the .cpp files you have in your project but it will not do this for each of the header files you have in your project. These .obj files are not actually needed to run your program and they can be safely discarded. They are just used as part of the compilation process.
Next Tutorial >>