0% found this document useful (0 votes)
7 views145 pages

Learn C++ Basics for Game Development

The document provides an introduction to C++, a programming language widely used in game development, highlighting its features, syntax, and basic programming concepts. It discusses the importance of learning C++, reasons to choose it, and includes examples of simple programs, variable types, and console input/output. Additionally, it emphasizes the significance of comments in code and introduces special characters used in programming.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views145 pages

Learn C++ Basics for Game Development

The document provides an introduction to C++, a programming language widely used in game development, highlighting its features, syntax, and basic programming concepts. It discusses the importance of learning C++, reasons to choose it, and includes examples of simple programs, variable types, and console input/output. Additionally, it emphasizes the significance of comments in code and introduces special characters used in programming.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link]

html

-main(), as the main function


-cout, as a command for writing to the console
-endl, as a line change command
-[Link](), as a command to wait for ENTER
Block, what is between brackets
Instruction, which always requires a ';' at the end
Comment, as a tool to help document the code

C++ - brief introduction


C++ is a programming language, created in 1983 by Bjarne Stroustrup. It is, so far, the
most used language in video games: C++ was used in 'bombs' like Far Cry, Half-Life 2,
Unreal Tournament 2004, and many others. I think I could hazard that 99% of the best games
In the last 10 years, they will have used either C (C++ is an evolution of the C language) or C++.
This language that you will learn will provide the foundations for the games that you will be able to make, whether they are
a text-based adventure, or a 3D game that will revolutionize the world. However, it does not
I would say it is easy to learn. Impatience may lead many to give up, as in the beginning.
you will see that the programs they will do will not be very appealing. But believe me, it's worth it!

4 reasons to learn C++


• it's ultra-fast - it's partly due to the games that computers (and especially the
graphics cards) have evolved in an astonishing way. Games are the programs that
they demand more from the computer and that is why the choice of professionals falls on C++.
• allows for various programming styles - while more modern languages, such as Java and
C# only allows programming using the Object-Oriented Programming paradigm.
C++ allows you to build programs using 4 different programming styles. By the way, the
initial programs will be made using the procedural paradigm, later it will be
used the Object-Oriented Programming paradigm.
• it is quite widespread - there is a lot of information about the language, disseminated in books and in
Internet. In addition, there are quite a few well-known libraries that work (and are found
well documented) with C++, such as OpenGL, DirectX, SDL, Lua, Havoc.
• it is the standard in the industry - if you want to enter the game programming industry you have to
that knowing this language. Furthermore, after learning this language well, they are
able to quickly use other similar languages, such as C# and Java.

Example 1.1 - The first program


#include <iostream>
using namespace std;

int main()
{
This is the first program of a future game programmer
endl;
[Link](); // Stops the program until the user presses a key

return 0;
}
[Link]

Example 1.1 - First Program


My first program was like this, only instead of written 'This is the first program of
a future game programmer" was the mythical "Hello World"
Iwillexplainlinebylinewhathappens.

#include <iostream>
O#include makes the content of the file that is in front of you, between <> (in this case the file
iostream) is to be included in the program. Without it, we couldn't use the cout command, nor endl.
These commands do not exist in pure C++, but thanks to the iostream library, they come to exist.
This library provides tools for the programmer to handle input and output, making it
life of the programmer much easier.
Don't worry if you haven't understood yet, we will learn in more advanced lessons.

using namespace std;


This instruction is also necessary to be able to use the command scoutend.
In summary, all the commands that are part of the standard (std) library of C++ are
within a namespace. Thus, it is necessary to show the compiler that we intend to use
(using) namespace std for access to the commands cout and endl.
This instruction will also be explained in future lessons.

int main()
Any C++ program must have a main function, which is the first function to be called.
By the program. A function in C++ is declared as follows:
return_type function_name(arguments)
{ instruções }
The return_type is the type of the return variable. In the case of the main function, it is oint (in English
integer), which means that the function will act until it finds an instruction (return) that returns a
integer value.
The function_name is the identifier (the name we call the function) and, as this is the function
principal is main.
The arguments are optional (in this example they are not used, so the '()' appear empty) and
will be explained later
Don't worry if you didn't understand the terms. The topic of functions will be explained in thelesson 6.

cout
The output represents the console output, which in this case is the window opened by the program. As if
It deals with the output, we want to 'send' text there, and we did this using the output operator.
Think of these symbols as a signal indicating the direction: we want to send
This is the first program of a future game programmer.
end the console output. It makes a lot of sense :P.

This is the first program of a future game programmer.


This is a string in C++. Strings are a set of characters and are defined between quotes "".
[Link]

end
Oendl(end line) causes a line break (it is the same as using ENTER in an editor.
texto)

[Link]()
The [Link] is a function that waits for the user to press a key, preventing that
The program would open and shut down immediately.

return 0;
Return causes the function to terminate and gives back (or "returns") a value to the function. In this case (in the
the main function serves to tell the main function to stop and returns the value 0, meaning that
Everything happened as expected. More about this in thelesson 6.

Concept of block
It is also worth mentioning the concept of a block. A block is what is inside curly braces in C++.
In this case, it serves to say that the code within the curly braces '{' '}' belongs to the main function.

Concept of instruction
Most of the mistakes made by aspiring C++ programmers (and it is a common mistake
In more experienced programmers :) it's the forgetting to put the ';' at the end of each statement.
Most of the time (in the less experienced programmer) this is due to the doubt of when to
you must put the ';'.
Each ';' must be placed at the end of each statement in C++. A statement can be defined as
one step. Every time we define something for the program to do, we have to put a ';' at the end.
There are some exceptions, such as preprocessor directives (those preceded by a '#',
like #include) and the definition of functions (they do not put ';' at the end of the braces of the functions).
Fortunately, the error is not very serious, since the compiler indicates it right away and only with practice is that
they will overcome it.

..............
At this point, they only need to know that the most basic structure of a C++ program is this.
You can change whatever is after "int main() {" and before "[Link]();" (adding
other scout, with other texts). They can also remove [Link]() to see the effect (the program opens and
date logo).

Comments
The comments serve to explain to other people what a part/instruction of the code does.
One can do without them, but it is recommended to use them frequently in order to understand.
improve the code.
There are 2 types of comments:
// One-line comment - Makes everything on that line a comment.
/* Comment that can be multiple lines */ - Causes everything following the /* to be a
comment, until finding the */.
[Link]

Tip:

Normally, at the beginning of each program, there is a brief description of the program. For example:

/**********************************

C++ Program
Autor: João Portela aka Agnor
December 23, 2004
Introduction to C++ Program

**********************************/

Example 1.2 - Prototype of a Game Menu


This is just a prototype of a menu. None of the commands work (obviously), it is for
just as a final example.
/**********************************

Example 1.2 - Prototype of a menu


Autor: João Portela aka Agnor
Data: 16 de Agosto de 2006
Prototype of a game menu,
just for reading.
[Link]

**********************************/

#include <iostream>
using namespace std;

int main()
{
Game Menu
cout << endl; //creates an empty line
cout << "1 - New Game" << endl;
2 - Continue Game
cout << "3 - Options" << endl;
4 - Help
5 - Credits

[Link](); // Stops the program until the user presses a key

return 0;
}

Example 1.2 - Prototype of a Game Menu


End of class 01 of C++:
Next classC++ 02 -Vavariables
Download thesource codetwo examples from the class
Download the class inPDF(experimental version)
[Link]

Go to the top of the page

Class 02 - Variables
<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-variable, as a tool to store values;


types of variables, understand the necessity of having various types of variables;
-cin, as a command to capture values entered by the user;
special characters, certain characters need to be 'written' in a special way to
they will be recognized by C++;

Variable
Variability is one of the most important concepts in programming. Putting it in a way
simple, remember math:
x = 23
y = 40
A variable is, therefore, a place in the computer's memory that stores a value. This value
it may be changed throughout the program (although we can also declare variables
constants).
In C++, variables are expressed in this way:
int x;
x = 20;
float pi = 3.14;
char character = 'a';
bool exit = false;
Let's go line by line:

int x;
Create a variable of type integer (int) (an integer number). At this moment, a number is assigned.
any to the variable, as we did not define a number.
[Link]

x = 20;
From now on, the variable x takes the value 20.

float pi = 3.14;
Create a variable of type float, that is, a number with decimal places.

char character = 'a';


Create a variable of type char (one character). Note that you can only insert one character. To insert
for multiple characters in a variable we will have to use arrays (will be explained inlesson 7)

bool exit = false;


Create a boolean variable (it can only contain 2 values: true or false)
respectively

Types of variables
Below are the essential types of variables in C++:
int - Integer number that ranges from -2,147,483,648 to +2,147,483,647. Takes up 4 bytes (32 bits)
float - Rational number (for example 1.8 or 1.62). Takes up 4 bytes.
double - the same as float, but has a greater range (e.g. 1.23413445123). Takes up 8 bytes.
char - Creates a text character. Values from -128 to +127 and occupies 1 byte.
bool - Creates a boolean variable. The values can be true or false (1 or 0, respectively).
Occupies 1 byte.
These are the essential types. Then there are several keywords that extend or shorten the scope.
of the variable. For example:
unsigned - the variable declared in front can only have positive values.
long - doubles the range of the variable, making it a variable with double the bytes.
short - reduces the range of the variable by half, making it a variable with half the bytes.
Example: short int a;
unsigned short int b;
long int c;
unsigned char d;
Most of the time we will only use the tipoint for integer numbers, the tipofloat for
decimal numbers, the char type (and later the string) for characters and strings (set of
characters) and the tipobool, for condition test variables.

Console Input
In the first class, we learned how to work with the console output (cout) that was used for the
programmer write on the screen what they wish. In this we will learn console input, which serves to
The user can write whatever they want on the screen (to be processed by the program). The Console Input is done
through the command line.
In this way, we will be able to make the user interact with the program, and that is truly
very important in game programming (otherwise it would just be a mere 'movie' and not an experience
[Link]

interactive).
I will show an example:
#include <iostream>
using namespace std;

int main()
{
int x;
cout << "Enter a number: ";
note the absence of endl. It is optional to put endl or not.
Let's experiment putting the endl to see the effect

cin >> x; // note that it is >> and not << because we are using input and not
output

You entered

[Link](); //in this case it is necessary to put 2 [Link]()


[Link]();
return 0;
}

Example 2.1 - Number entered by the user


Hummm.... It's already a bigger program... let's go line by line (I will ignore what we have already learned)

int x;
Create a variable of type integer, named x.

Enter a number:
Como tinha dito, não é mesmo preciso usar oendl. Poderiam ter usado oendl, mas assim o número
didn't appear in front of the two points, but in the next line. The best thing is to try it out of
2 ways.

cin >> x;
Make the variable x have the value that the user entered. Basically this command
wait for the user to press ENTER and keep the value that the user entered before
ENTER. Remember the example of the signal below: we are sending the content of the cin (what
the user wrote) for the variable x)

You entered
We are sending a string (You typed...) and a variable (x) to be displayed in the console.
output
They noticed that at the beginning of the sentence there is a somewhat strange character. This character ' ' causes
move to a new line. Oendlt also does this, but it's better to use the character ' ' at the beginning of the sentence and
end of line.
Tip:
[Link]

Notice that I used [Link]() twice;

If [Link](); does not work properly replace it with system("PAUSE"); and include
the stdlib.h file

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
...
system("PAUSE");
return 0;
}

Use the command [Link]() twice.


[Link]();
[Link]();

Special characters
Since we are at the end of the class, I will talk to you about some special characters. You know one: the
'\n'
I will put here a table with the characters and a brief explanation of each one:
Character Description
\a bell, emits a sound
\b backspace
\0 terminator character
\f page start
\n line change
\r line start
\t horizontal tab
\v vertical tab
\\ backslash
\' fold
\" quotes
oo character whose code in octal is ooo
\hh character whose hexadecimal code is hh
This table was taken from the site ofPedro SantosBy the way, that site has a very good C++ tutorial.
good (I learned C++ with this tutorial) and I think everyone should spend some time reading it, because
If you don't understand something in this tutorial, you can always see if you understand with another one.
The site [Link]/cpptutorial/
[Link]

Example 2.2 - Guess the number (Version I)


#include <iostream>
using namespace std;

int main()
{
int number = 8; //choose any number
int attempt; //the user's attempt

cout << "GUESS THE NUMBER - VERSION I" << endl;


Enter your guess (1-10):
cin >> attempt;

You chose the number \'


cout << "The number chosen by the programmer is '" << number << "'.";
endl;

You got the first one right, congratulations!


If you didn't get something right, tell me that you will get it right next time :)

[Link]();
[Link]();
return 0;
}

Example 2.2 - Guess the number (Version I)


End of lesson 02 of C++:
Next classC++ 03 -Vavariables
Download thecódigo fonte two examples from the lesson
Download the lesson in PDF (Coming Soon)

Go to the top of the page

Lesson 03 - Arithmetic Operations


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-affection, '='
addition, '+'
[Link]

subtraction
multiplication, '*'
division, '/'
-module, '%'

Arithmetic operations
No programming language would be complete without support for arithmetic operations. The
game programming requires a lot of calculations, for example, the decrease of Health Points, the
increase in movement coordinates, etc..
Let's start with the simplest types of arithmetic operations:
int x = 4 + 2; addition
int y = 4 - 2; subtraction
int z = 4 * 2; multiplication
int a = 4 / 2; division
Simple, right? If we now wanted to show the value of x, y, z, a, we would add this:
x = x
y =
cout << "z = " << z << endl;
a =
Below is a table with the most frequent arithmetic operations. This table was taken from
Pedro Santos' C++ Tutorial:
operator exemplo description
= a = b = c; affection, the example would have the following result a = ( b = c )
+ a = b + c; sum, affects variable a with the sum of b and c
- a = b - c; subtraction affects variable a with the difference between b and c
* a = b * c; multiplication affects a with the product of b and c
/ a = b / c; division, affects with the result of the division of b by c
% a = b % c; module, affects how the remainder of the division of b by c
From here I think you are familiar with most of the operators. However, there is one that
nobody (that I know) learned in school, that is the operator %. This operator (very useful for
modulus) returns (or "returns") the remainder of the division between 2 numbers.

For example: 20 % 3 gives 2 because 20 divided by 3 does not give an integer, so it becomes 18.
to divide by 3 plus the remainder of 2. Some examples:
7 % 4 -> dá 3
6 % 4 -> gives 2
10 % 5 -> gives 0, because 10 divided by 5 gives 2 exact, there is no remainder.

We will learn its usefulness when we talk about generating random numbers.
As for the assignment, it is used to give a value to a variable. For example:
int a = 8;
int b = 2;
int c;
c = a + b; c is equal to 10
c = c + b; c is equal to 10 + 2 = 12
[Link]

c = c / b; c is equal to 12 divided by 2 = 6
b = c; // b will be equal to c = 6
To make our lives a little easier, C++ has other ways to assign variables. Take a look at them in
following table (also from the site ofPeter Saints):
operator the same as:
a += b; a = a + b;
a -= b; a = a - b;
a /= b; a = a / b;
a multiplied by equals b; a = a * b;
a %= b; a = a % b;
++a; a = a + 1;
--a; a = a - 1;
I think it's all easy to understand, just a small example:
int a = 6;
int b = 4;
b += 3; b is equal to b + 3 = 4 + 3 = 7
b -= a; b is equal to b - a = 7 - 6 = 1
b++; // b is equal to b + 1 = 1 + 1 = 2
b--; // b is equal to b - 1 = 1
In C++, parentheses '()' can also be used to define priorities in arithmetic instructions.
For example:

(2 + 3) * 2. This equals 10.


2 + 3 * 2. This equals 8, as multiplication takes precedence over addition.

The First Useful Program: A Sum Calculator


#include <iostream>
using namespace std;

int main()
{
int a, b, c;
Enter the first number, press ENTER and enter the 2nd:
<< endl;
cin >> a >> b;
c = a + b;
The sum of the 2 numbers is equal to
[Link]();
[Link]();
return 0;
}

Example 3.1 - Addition Calculator


Let's go line by line:

int a, b, c; // The same as int a; int b; int c;


cin >> a >> b is the same as cin >> a; cin >> b;
[Link]

c = a + b; -The variable c becomes the sum of the variable a and the variable b.

The rest of the program should be easy to understand.

Relational Operators
In addition to arithmetic operators, there are other operators in C++ that are used to compare values.
For example, we will be able to know if a certain variable has the same value as another, or if
there is a greater or lesser value. See the table below:
operator meaning
== equal to
!= is not equal to
> greater than
>= >=
< less than
<= less than or equal to
The result of using these operators is a boolean variable. If you check the condition above,
Then the variable will be equal to 1 (true). If not, it will be equal to 0 (false). Look at the following
example program that explains everything about relational operators:
#include <iostream>
using namespace std;

int main()
{
int a, b;
bool varteste;

COMPARISON PROGRAM
Enter two values (enter the first, press ENTER and
then insert the second):; //this was just to show that this
it is possible
//see explanation in the note below
cin >> a >> b;

varteste = a == b; // varteste will take the value of 1 if a is equal to b


cout << "Equality between " << a << " and " << b << " is equal to " << varteste
end line;

varteste = a > b;
Test of superiority of
<< varteste << endl;

varteste = a < b;
Test of inferiority of
<< varteste << endl;

cout << "\n\nCodigo: \n\n0 -> Falso\n1 -> Verdadeiro" << endl;

[Link]();
[Link](); // Stops the program until the user presses a key

return 0;
}
[Link]

Example 3.2 - Relational Operators


End of class 03 of C++:
Next classC++ 04 - Logical and Conditional Operators
Download thesource codetwo examples from the class
Download the class in PDF (Soon)

Go to the top of the page

Class 04 - Logical and Conditional Operators


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-AND(&&), e
OR(||), or
NOT(!), it is not
-if, yes
else, otherwise
else if

Logical operators
Os operadores lógicos são, talvez, um bocado difíceis de compreender, uma vez que não fazem
part of basic mathematics. To give a simple example:
Imagine that we wanted to know if the HP (Hit Points) of a character is within range.
between 0 and 100. We could do it this way:
#include <iostream>
using namespace std;

int main()
{
int min = 0, max = 100; //minimum and maximum HP values
bool varteste; //the variable for verification
int value; //the value to be entered by the user

CHECKING HP LIMIT
[Link]

Insert a HP value:
cin >> value;

varteste = valor >= min && valor <= max;


/*
If the value is greater than or equal to the minimum AND the value is less than or equal to the
maximum, then varteste is true
*/
cout << "The test is equal to " << varteste << endl;

Code: 0 -> False 1 -> True

[Link]();
[Link](); // Stops the program until the user presses a key

return 0;
}

Example 4.1 - Verification of HP Limit


The character && (AND) is the only new thing. For a better explanation, I created some tables of
each of the three logical operators:

Operator && (AND, and):


A B Result (A && B)
false false false
false true false
true false false
true true true
Is AeB true?

Operator || (OR, or):


A B Result (A || B)
false false false
false true true
true false true
true true true
It reads: Is AouB (any of them) true?

Operator ! (NOT, is not)


A Resultado (!A)
false true
true false
It reads: the opposite of A.
[Link]

It's a practical example:


bool a = true;
bool b = true;
bool c = false;
bool d = false;
bool e;

e = a && c; // e vai ser igual a false


e = a && b; // e will be equal to true
e = c && d; // e will be equal to false

e = a || c; // e will be equal to true


e = a || b; // e will be equal to true
e = c || d; // e will be equal to false

e = a == c; // e will be equal to false


e = a == b; // e will be equal to true
e = c == d; // e will be equal to true

e = !a; // e will be equal to false


e = !c; // e will be equal to true

Conditional operators: If
We have now reached one of the most important points in programming, conditional operators.
Anyone who has never programmed and is reading this course must have at some point wondered how it is possible through
With simple sets of instructions (most of them mathematical), we can create games.
So far we haven't built very interactive games (we can even say that we haven't created games
none :), they are more pieces of text that we send to the user. The conditional operators will
enable this interaction.
For example, imagine that we wanted to know if the player died to show a message of
Game Over. What would we need? First a variable of HP (Health Points or Points)
of Life). We would also need to use the less than or equal operator (to know if the HP is less
or equal to 0). Let's create a program with what we know so far:
#include <iostream>
using namespace std;

int main()
{
bool varteste; //the variable for verification
int hp; //the health points

cout << "GAMEOVER PROGRAM 0.1" << endl;

Enter a HP value:
cin >> hp;

varteste = hp <= 0; //so far nothing new...

cout << "The test is equal to " << varteste << endl;
[Link]

Code: 0 -> False 1 -> True

[Link]();
[Link](); // Stops the program until the user presses a key

return 0;
}

Example 4.2 - Game Over Program 0.1


With the previous knowledge we could only arrive at this, but this is not what we want.
We want the program to display a text saying 'Game Over'. For that, we will use the
conditional operator IF.
If it is true, then 'Game Over' will be displayed.
#include <iostream>
using namespace std;

int main()
{
bool varteste; //the variable for verification
int hp; //health points

cout << "PROGRAM GAMEOVER 1.0" << endl;

Enter a HP value:
cin >> hp;

varteste = hp <= 0; // so far nothing new...

if (varteste) //if varteste is true...


{
Game Over
}

[Link]();
[Link](); // Stops the program until the user presses a key

return 0;
}

Example 4.3 - Game Over Program 1.0


Let'sgostepbystep:
if (condition)
{
...instructions
}
If the condition (which is in parentheses) is true, then the instructions will be
executed. Note the use of braces. These are only necessary if the block has more than one
instruction.
We can also put the condition directly in the if, without needing a boolean variable:
#include <iostream>
[Link]

using namespace std;

int main()
{
int hp; //the health points

PROGRAM GAMEOVER 1.01

Enter a value for HP:


cin >> hp;

if (hp <= 0) //if the HP is less than or equal to 0...


{
Game Over
}

[Link]();
[Link](); // Pauses the program until the user presses a key

return 0;
}

Example 4.4 - Game Over Program 1.01


This code is much better, both in terms of performance (it is shorter and does not use a variable.
boolean) as well as readability: it is much easier to understand the condition. If the HP is less than or
equal to 0, then show the phrase 'Game Over'.
I only used Example 4.3 to demonstrate how the if works: if what is in parentheses
if (condition) is true (equal to 1), then execute the instructions that are part of the if (usually
as those in the following block).
Tip:

The if condition, if it has only one statement, does not have to have braces. For example:

if (hp <= 0)
Game Over
[Link]();

In this case, cout << "Game Over" << endl; would be part of the instructions to be executed by the if,
while [Link]() does not.

However, you are encouraged to continue using brackets with an instruction, as it allows for greater
readability in the code (anyone will easily know when the if starts and ends).
Tip:

In the first lesson, I already talked about a block. Now the concept of a block is more important. A block
It is used to group several instructions into a single instruction and is defined between curly braces ('{' and '}'). It is
That's why we can choose not to use braces in an if condition, if it only has one.
instrução. Se tivermos mais que uma temos que usar um bloco (através das chavetas).
Tip:
[Link]

Surely you noticed the 3 different versions of the GameOver program.

Version 0.1 means that the program is still in an experimental phase, it has not yet reached
necessary to reach 1.0. This is due to the program not yet displaying the Game Over message.
Version 1.0 means that the Game Over program has already achieved its purpose, it is the first version.
that fulfills the objective.
Version 1.01 means that slight changes were made to the program (the elimination of the variable.
varteste).

Further down we will develop version 1.1, a slightly modified version of the program.
(with more visible changes).

Conditional operators: Else and Else if


Let's learn now the conditional operators else and else if. These operators serve to
complement to the operator if.
Below is example 4.5: Game Over Program 1.1, which uses the else operator:
#include <iostream>
using namespace std;

int main()
{
int hp; //the health points

cout << "GAMEOVER PROGRAM 1.1" << endl;

Enter a HP value:
cin >> hp;

if (hp <= 0) //if the HP is less than or equal to 0...


{
Game Over
}
else // otherwise (if HP is not less than or equal to 0)...
{
You managed to survive!
}

[Link]();
[Link](); // Pauses the program until the user presses a key

return 0;
}

Example 4.5 - Gameover Program 1.1


I think it won't be very difficult to understand what he does. If the previous if is not met,
So it will fulfill what is inside the else. It is then necessary to have an if condition preceding the else.
(cannot exist alone).
Agora vou mostrar a condiçãoelse if, criando um menu de um jogo interactivo:
#include <iostream>
using namespace std;
[Link]

int main()
{
int choice;

GAME MENU
1 - New Game
cout << "2 - Load Game" << endl;
cout << "3 - Options" << endl;
cout << "4 - Exit" << endl;

cin >> choice;

if (choice == 1)
You chose to start a new game

else if (choice == 2)
You chose to load an old game

else if (choice == 3)
cout << "Options:" << endl;

else if (choice == 4)
Do you really want to leave?

else // Otherwise...
Wrong choice

[Link]();
[Link]();
return 0;
}

Example 4.6 - Game Menu


I don't find it very difficult to understand. First, we have if. If the choice is equal to 1, execute the
instruction (or block). Otherwise (else) if (if) the choice is equal to 2....
Let's try to compile the program and change the texts. Basically, it is like this:
Program:

Show the menu,

Wait for the user to provide a value.

If the value is equal to 1


It displays on the screen: You chose to start a new game

If the value is not equal to 1,


If the value is equal to 2
Write on the screen:...... (you know ;)

If the value is not equal to 2,


If the value is equal to 3
Write on the screen:...... (you know it ;)
[Link]

If the value is not equal to 3,


If the value is equal to 4
Write on the screen:...... (you know ;)

If the value is not equal to 4 (therefore different from the other values above),
Wrong choice

The First Game: Guess the Number


Yes, after 4 C++ classes you can already make a game!!! Here is the code:
#include <iostream>
#include <stdlib.h> // to be able to use system("PAUSE");
using namespace std;

int main()
{
int number = 6;
int user;

cout << "*********************************" << endl;


cout << " ADIVINHE O NÚMERO " << endl;
cout << "*********************************" << endl;

Please enter a number: _


cin >> user;

if (user == number)
{
CONGRATULATIONS!!!! YOU GOT IT RIGHT
}

else if (user < number)


{
You didn't get it right :( Too low
}

else if (user > number)


{
You did not get it right :( Too high
}

[Link]();
[Link]();
return 0;
}

Example 4.7 - Game - Guess the Number


I give you homework to understand what the program does :P
This is the first game! There is still a lot missing, like the first number (it's always 6 and not another), and a
option to try again, but what do they want? We haven't learned much yet, but we've already done a
game!
[Link]

End of class 04 of C++:


Next classC++ 05 - More Conditional Operators
Download thesource codetwo examples from the lesson
Download the class in PDF (Coming Soon)

Go to the top of the page

Class 05 - More conditional operators


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-switch, analyze the variable


-case, in case the variable analyzed by the switch is...
-break, exit the switch, preventing other instructions from being executed
while
-do...while, different from the while operator in the order of execution
for, as an alternative to while
ternary operator, as an alternative to if...else

The switch operator


At this point in the classes, you already know how to create a game's menu (as you saw in the previous class).
Let'sremember:
#include <iostream>
using namespace std;

int main()
{
int choice;

GAME MENU
1 - New Game
cout << "2 - Load Game" << endl;
3 - Options
4 - Exit

cin >> choice;

if (choice == 1)
[Link]

You chose to start a new game

else if (choice == 2)
You chose to load an old game

else if (choice == 3)
Options:

else if (choice == 4)
Do you really want to exit?

else // Otherwise...
cout << "Wrong choice" << endl;

[Link]();
[Link]();

return 0;
}

Example 4.6 - Game Menu


This simplification task. Let's see how the program would look with switch:
#include <iostream>
using namespace std;

int main()
{
int choice;

GAME MENU
1 - New Game
cout << "2 - Load Game" << endl;
3 - Options
4 - Exit

cin >> choice;

switch (choice)
{
case 1: // if the choice is 1

You chose to start a new game


break;
case 2: // case if the choice is 2
You chose to continue an old game
break;
case 3: // case if the choice is 3

cout << "Options:" << endl;


break;
case 4: // case if the choice is 4
Are you sure you want to exit?
break;
default: // case it is none of the choices
[Link]

Wrong choice, please try again


}

[Link]();
[Link]();

return 0;

Example 5.1 - Game Menu (Version 2)


The structure of the switch can be explained this way:
switch (variable) //checks the value of the variable
{
case n: // case if its value is n (any value)...
//...
default: //otherwise...
//...
The only command that should be strange is the commandbreak.
He tells us to immediately leave the switch, if we don't put the program.
executed all the instructions that are in the switch (it showed us the 5 texts instead of just appearing)
that the user wanted). Try removing obreake and running the program.
We can also group several cases like this:
#include <iostream>
using namespace std;

int main()
{
int choice;

Would you like to know the number of days in which month? 1 - 12

cin >> choice;

switch (choice)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: //in case it is 1 or 3 or 5 or 7 or...
This month has 31 days
break;

case 4:
case 6:
case 9:
case 11: //in case it is 4 or 6 or 9 or 11...
This month has 30 days
[Link]

break;

case 2: //if it is 2 (February)


This month has 28 or 29 days
break;

default: // case it is none of the choices


cout << "Wrong number" << endl;
break;
}

[Link]();
[Link]();

return 0;

Example 5.2 - Number of days in a month


As you can see, grouping cases is very useful. Otherwise, we would have to repeat quite a few times the
same instruction.

While operator
The while operator creates a loop, which is very useful in game programming. For example,
within a game there is a cycle that ends when the player wants to turn off the game. An example:
#include <iostream>
using namespace std;

int main()
{
int choice;
bool done = false; /* boolean variable (true or false) in case it is
false continues to execute the main loop if it is
true exit from the cycle

while (done == false) //while done is equal to false....

{
Welcome to this annoying program, do you want to see it again?
<< endl;
1 - Yes 2 - No
cin >> choice;

switch(choice)
{
case 1:
break; // exit the switch

case 2:
done = true; // done will be equal to true, thus it exits the while
break;
default:
break;
[Link]

//back to the beginning of the while....


}

return 0;
}

Example 5.3 - Annoying Program


This will be very useful for, for example, creating a Loading Game window.
of the game, etc.
Tip:

Instead of using

while (done == false)

we could use

while (!done)
The while structure can be seen this way:
while (condition) //as long as the condition is true...
{
execute these instructions
}
Notice:

Beware of infinite loops! These loops are created when it is impossible for the user
exit the program. For example, if they remove the second case from the program, the user will not
will manage to exit the program (infinite loop)

The do...while operator


There is a small difference between While and Do...While. Let's see this example:
#include <iostream>
using namespace std;

int main()
{

while ([Link]() != '*') //while [Link]() is different from *


(asterisco)

{
Welcome to this annoying program (version 2).
If you want to exit, press * followed by ENTER

//back to the beginning of the while....


[Link]

return 0;
}

Exemplo 5.4 - Programa Irritante (Versão 2)


If you try the program, you will see that you first have to press ENTER for it to appear.
message. Why? Because the condition while first tests the condition. If it is true, it executes
the instructions.
In this example, to test the condition we first have to press ENTER (try it on
start writing * and then press ENTER).
Odo...while makes the instruction execute first, and only then it tests it:
#include <iostream>
using namespace std;

int main()
{
do
{
Welcome to this annoying program (version 3).
If you want to exit, press * followed by ENTER

}
while ([Link]() != '*'); //don't forget the ;

return 0;
}

Example 5.5 - Annoying Program (Version 3)


This version is much better! Only by trying it out can you really understand the difference.
two.

The condition for


The condition 'for' is also very used. Let's see this example with 'while':
#include <iostream>
using namespace std;

int main()
{
int x = 0;

while (x < 5) // while x is less than 5 ...


{
cout << 'X is equal to ' << x << endl;
x++; //increments x ( x = x + 1 )

}
[Link]

[Link]();

return 0;
}

Example 5.6 - X is equal to ... (up to 5)


How it improves this type of code is much better:
#include <iostream>
using namespace std;

int main()
{
for (int x = 0; x < 5; x++)
{
cout << "X is equal to " << x << endl;
}

[Link]();

return 0;
}

Example 5.7 - X is equal to ... (up to 5) (Version 2)


This may seem a bit complicated. But it's not!
Let's analyze the gift:

for (int x = 0; x < 5; x++)


We have the first instruction, which is the initiation of the for loop (it will only be executed once).
Variables are usually declared here.
Then we have the second, which is the test for the condition. If true it executes the for, if false it executes the
block.
The last instruction to be executed is usually an increment (x++).
The for operator becomes very useful when we want to perform something repeatable a certain number
times.

The ternary operator


To finish, I will show you the ternary operator. Let's see an example using if else:
#include <iostream>
using namespace std;

int main()
{
int a;
int b = 10;
bool greater;

cout << "Enter a number: ";


cin >> a;
[Link]

if (a <= b)
{
maior = false;
}
else
{
maior = true;
}
[Link]();
[Link]();

return 0;
}

Example 5.8 - Greater of two numbers


And using the ternary operator:
#include <iostream>
using namespace std;

int main()
{
int a;
int b = 10;
bool maior;

Enter a number:
cin >> a;

a > b ? maior = true : maior = false;


Is a greater than b? If so, greater is equal to true, if not, greater is equal
a false.

[Link]();
[Link]();

return 0;
}

Example 5.9 - Greater of two numbers (version 2)

Guess the Number Game (Version 1.1)


This version has new features: it only exits the program when the user guesses the number.
and shows the number of attempts made. The code below:
#include <iostream>
using namespace std;

int main()
{
int number = 21; //the number to be guessed
[Link]

int value; //the number to be entered by the user


int attempt = 0; //the number of attempts that the user needed
bool done = false;

cout << "Welcome to version 1.1 of the GUESS THE NUMBER game" << endl;

while (!done)
{
Enter your attempt:
cin >> value;

attempt++; //increments the number of attempts

if (number == value)
{
Good, you got it on the
You have to leave the game, since you already know the number :)
endl;
done = true; //sai do while
}

if (value < number)


{
The number is too low. Try a higher one.
}

if (value > number)


{
The number is too high. Try a lower one.
}
}

[Link]();
[Link]();

return 0;
}

Example 5.10 - Game - Guess the Number 1.1


I leave you again the task of understanding what the program does for homework.
End of class 05 of C++:
Next classC++ 06 - Functions
Download thesource codetwo examples from the class
Download the lesson in PDF (Coming Soon)

Go to the top of the page


[Link]

Class 06 - Functions
<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-function, how to declare, define and use it


-arguments, like the parameters passed to functions
Scope, a variable within a function can only be accessed by that function.
return, return values outside the function
do...while, different from the while operator in the order of execution
for, as an alternative to while
ternary operator, as an alternative to if...else

Functions
A function is a set of instructions that can (and should) be reused (used more than once)
time), at any point in the program. So far we have always used one function: the function
main.
They are very useful because they allow many lines of code to be replaced in one go.
For example, the following code would be possible as I explained in thefirst classthe main function
always the first to be called by the program Finally we have arrived at one of the most
fun programming with C++: functions! This is because we can create functions to
practically everything and then use them. For example, we could do:

drawCharacter();
moveCharacter();
showVideo(VIDEO_SEQUENCE_23);

In summary, a function is a simple line of code that allows you to execute several lines more.
complex.
Vou criar uma função simples para perceberem a ideia:
#include <iostream>
using namespace std;

int createCharacter()
{
Character Created. Name: Agnor
return 0;
}
[Link]

int main()
{
createCharacter();
[Link]();
return 0;
}

Example 6.1 - Create Character Function


Nafirst lessonvimos a estrutura básica de uma função:
return_type function_name (arguments)
{ instruções }
This function follows a structure similar to the main function: it has no arguments and the return type is
umint.
However, this function can be called by other functions (in this case, it is called by the function
main). For example, the following code is possible:
#include <iostream>
using namespace std;

int createCharacter()
{
Character Created. Name: Agnor
return 0;
}

int main()
{
createCharacter();
criarPersonagem();
createCharacter();
[Link]();
return 0;
}

Example 6.2 - Using the same function to create multiple characters


As you can see, functions greatly help shorten the code and in its understanding (we have a
line of code, instead of 200, for example). Furthermore, if we want to change the way to create
characters, just change it only once (the function), there is no need to change the code each time
point.

Function Arguments
A given function can have several (or none) arguments. The arguments (or parameters) of
a function is used for the programmer to pass some variables to the processing function. For example,
if we wanted to create a Sum function (the objective of which would be to show the sum of two numbers),
we would have to pass two variables to the function.
The arguments are found within the parentheses '()' of the function and present the type of variable and the
identifier ("int x", for example). A function can have as many arguments as we want. See the
following example:
[Link]

#include <iostream>
using namespace std;

************* SUM FUNCTION ****************


Show in output the value of a + b
******************************************/
int sum(int a, int b)
{
int value = a + b;

The sum of

return 0;
}

int main()
{
soma(8, 19); // 8 is the value that 'a' will assume and 19 the value of 'b'
soma(21, 32);
sum(26, 27);
sum(1, 1);
soma(5, 2);

[Link](); // Pauses the program until the user presses a key

return 0;
}

Example 6.3 - Sum of two numbers 1.0


Here you can see the versatility of the functions: with just a few lines of code we have a
totally customizable adding calculator. For example, instead of the environment in mode of
text, we could create a completely 3D environment without needing to change the code
inside the main function.

Basic concepts of scope


A variable that is declared within the block of a function (or in the arguments) only exists
within it. Thus, the example below is incorrect:
#include <iostream>
using namespace std;

int sum (int a, int b) //a and b only exist within the sum function!
{
int valor = a + b; // value only exists within the sum function!

The sum of

return 0;
}

int main()
{
a = 5; //erro... 'a' só pode ser usado dentro da função soma

int a; //this 'a' is different from the 'a' inside the sum function
[Link]

a = 4; //correct, because 'a' exists within the main function, but it is


different from 'a' that is in the sum function

[Link](); // Pauses the program until the user presses a key

return 0;
}

Uncompilable example - Introduction to scope in functions


There is a lesson dedicated to variable scope,lesson 10, where this theme will be seen in detail.

Return of Values
So far we have always used the return instruction at the end of each function, but without knowing its
true meaning. The function combined example 6.3 is still limited, as the
the programmer cannot access the variable "value" (the variable that contains the sum). The instruction return
returns a value that is within the function. In the case of the calculator, we will use the
instructionreturn value;
#include <iostream>
using namespace std;

int sum (int a, int b) //a and b only exist within the sum function!
{
int valor = a + b; // value only exists within the sum function!

return value;
}

int main()
{
int a; //as you know, these two values are not the same as those that are
int b; //inside the sum function
int result;

cout << "Enter the first value: ";


cin >> a;

Enter the second value:


cin >> b;

result = sum(a, b); // result will be equal to the value returned by


//sum function
The sum of the two entered numbers is
endl;

[Link]();
[Link]();

return 0;
}
[Link]

Example 6.4 - Sum Function 2.0


It is also possible to create a function that does not return anything. This function must be of the void type.
(empty). It is noteworthy that, according to C++ standards, the main function must necessarily be to
tipoint:
void speak()
{
Welcome:
//no return!
}

Declaration and Definition of functions


When we do:
int a; - we are just declaring a variable
a = 5; - we are defining the variable
int b = 5; - we are declaring and defining a variable
The functions also follow this scheme. So far we have declared the function and defined it to the
at the same time, but we can declare first and define only at the end:
#include <iostream>
using namespace std;

int sum(int a, int b)


{
return (a + b); //we don't need to create an intermediate variable
}
we are declaring and defining the function at the same time

int subtraction(int a, int b);


int multiplication(int a, int b);
int division(int a, int b);
/* we only made the declaration, the definition is below. Note the presence of
semicolon ';', as in variable declaration */

int main()
{
int a, b;

cout << "Enter two values:" << endl;


cin >> a >> b;

cout << "\nSum: " << sum(a, b) << endl;


cout << "Subtraction: " << subtraction(a, b) << endl;
cout << "Multiplication: " << multiplication(a, b) << endl;
cout << "Division: " << division(a, b) << endl;

[Link]();
[Link]();

return 0;
}

/*FUNCTION DEFINITIONS*/
[Link]

int subtraction(int a, int b)


{
return (a - b);
}

int multiplication(int a, int b)


{
return (a * b);
}

int division(int a, int b)


{
return (a / b);
}

Example 6.5 - Calculator 1.0

Random Function
I will put here a function that will be very useful: The random function. This function generates numbers
random!
#include <iostream>
#include <stdlib.h> //to be able to use rand()

#include <windows.h> //to be able to use GetTickCount()


using namespace std;

/***********************************************************
int getRandom(int from, int to)
generates random numbers that range from "from" to "to"

***********************************************************/

int getRandom(int start, int end);

int main()
{
srand( GetTickCount() ); //I will explain this when talking about arrays.
Let's try to remove and run the program
several times!
for (int x = 0; x < 10; x++)
cout << getRandom(0,5) << endl; // braces are not necessary because it's only
a line

[Link]();
return 0;
}

int getRandom(int from, int to)


{
int random;
ate -= de;
random = rand() % (ate + 1) + de;
return random;
}
[Link]

Example 6.6 - Function getRandom


Osrand() do not need to be understood for now, they just need to know that without it the program generated
the same numbers every time we start it (try removing it, just for experimenting and creating it)
that learn programming).
I will just try to explain the line: random = rand() % (up to + 1) + from;
What orand() does is generate a random number (which could be например 9828383893 or
36). As we want to limit the number to a certain value, we use the modulus or remainder (%). So if
The remainder of 36 when divided by 5 is 1, that's why the number will be 1. However, it only generates numbers from 0 to
4e not until 5. That's why we add one more value. This makes it add the desired value.
lineate -= defaz makes it so that it only adds the difference entreateede.
Confused? Right now they just need to know that it works!

Guess the Number Game - Version 2


I leave it as homework for you to understand what this new version of the number guessing game does.
There's just one thing I haven't mentioned yet: global variables, but I think they speak for themselves:
/********************************************
GUESS THE NUMBER
Versão: 2.0
Autor: João Portela a.k.a. Agnor
Development Date: March 27, 2005
*********************************************/

#include <iostream>
#include <stdlib.h> //to be able to use rand()
#include <windows.h> //to be able to use GetTickCount()
using namespace std;

/* GLOBAL VARIABLES
These variables can be used by all functions of the program!

int choice; //the user's choices


int number; //the number to guess
int AttemptCounter; //counts the number of attempts
int numeroTentativa; //numero disponivel de tentativas
bool done = false;

void Hint(int choice); //shows a hint


void Menu(); // game menu
void inGame(); //inside the game
void newGame(); //creates new game
void Won(); //message shown to the winner
void Lost(); //... to whom lost

int getRandom(int de, int ate) //generates random numbers


{
int random;
ate -= from;
random = rand() % (ate + 1) + de;
return random;
}

int main()
{
[Link]

srand(GetTickCount());
cout << "Bem-Vindo ao JOGO ADIVINHA O NUMERO - VERSAO 2" << endl;
For Joao Portela a.k.a. Agnor

while(!done)
{
Menu();
}

[Link]();
return 0;
// Did you see that small main? :P
}

void Menu()
{
What do you want to do?
1 - New game
cout << "2 - Exit" << endl;
cin >> choice;

switch(choice)
{
case 1:
newGame();
break;
case 2:
done = true; //ends the do while loop
break;
default:
Error...Wrong key
Menu(); //returns to the menu
break;
}
}

void newGame()
{
ContadorTentativa = 0;
Choose the difficulty level:
1 - 1 to 10
2 - 1 to 20
3 - 1 to 30
4 - 1 to 40
And from there onwards :P
cin >> choice;

if (choice <= 0)
{
Error, number is less than or equal to 0... Starting with level 1
endl;
escolha = 1;
}

You chose from 1 to

numeroTentativa = escolha + 1;
[Link]

number = getRandom(1, 10*choice);

inGame();

void inGame()
{
if ((attemptNumber - AttemptCounter) > 0)
{
Number of remaining attempts:
AttemptCounter << endl;
Enter a number:
cin >> choice;
AttemptCounter++;

if (choice == number)
{
Won();
}

else
{
Tip(choice);
}
}

else
{
Lost();
}
}

void Won()
{
Congratulations, You Won!!!
}

void Lost()
{
You might have more luck next time... you lost...
endl;
}

void Suggest(int choice)


{
if (choice < number)
You need to bet higher
else
You have to bet lower

inGame();
}

Exemplo 6.7 - Jogo Adivinha o Número 2.0


[Link]

End of class 06 of C++:


Next classC++ 07 - Arrays
Download thesource codetwo examples from the lesson
Download the class in PDF (Coming Soon)

Go to the top of the page

Class 07 - Arrays
<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-array, as a group of variables with the same identifier


-strings, a set of characters, usually placed in an array
two-dimensional arrays, commonly used in maps

Arrays
Arrays are a 'group of places in memory that have the same name and store the same type.'
of data.
To explain better, an example:
Imagine that we are creating a program that calculates the weekly average temperature.
considering, for example, these values:

Day Temperatura (ºC)


Second 15
Tuesday 19
Fourth 19
Fifth 17
Friday 16
Saturday 20
Sunday 14
So far the easiest way would be to create 7 integers... But it isn't. Seven integers is not too much work,
But imagine it would be for 30 days. What names will you come up with? int day1, int day2, int day3....
[Link]

Arrays simplify a lot. They are declared like this:


int days[7];
We have here an array of 7 integers, ranging from number 0 to 6. Here is an example
practical
#include <iostream>
using namespace std;

int dias[7]; //creates an array of 7 characters (from dias[0] to dias[6])

int main ()
{
for(int n = 0; n < 7; n++)
{
cout << "Enter the value of the " << n + 1 << "th day: " << endl;
//n + 1 because in C++ the array starts at 0 instead of 1
cin >> days[n];
}

int average = ( days[0] + days[1] + days[2] + days[3] + days[4] + days[5] +


days[6] ) / 7;
The weekly average of the temperatures is

[Link]();
[Link]();
return 0;
}

Example 7.1 - Calculate the weekly average of temperatures


The arrays start at 0 (days[0]) that's why I made int n = 0 instead of int n = 1.
Nocout << "Enter the value for the " << n + 1 << "th day: " << endl; on + 1 serves for the number
do dia visualizado ser apresentado correctamente... Abaixo iremos ver o uso do operador for

Filling arrays using the for operator


A simple way to fill arrays is by using the for operator. In the following example, we will see
how to fill an array with a number chosen by the user:
#include <iostream>
using namespace std;

int main()
{
int MAX_ELEMENTS = 10; //the maximum number of elements in the array

int arr[MAX_ELEMENTS]; //declares an array with a predefined number of


elements

int value; //value of each element in the array (is equal...)

Enter the value to be assigned to each element of the array:


cin >> value;

for (int i = 0; i < MAX_ELEMENTS; i++)


{
[Link]

arr[i] = value; //will traverse the array from 0 to MAX_ELEMENTS


}

[Link]();
[Link]();

return 0;
}

Example 7.2 - Assign a value to all elements of the array


In the example above, the program will go through all the elements of the array, starting at 0 (int i =
0), ending at MAX_ELEMENTS (i = MAX_ELEMENTS) and incrementing i by 1 (i++). It is
a rather simple way with little code.
Now we will see how to assign a custom value to each element of the array:
#include <iostream>
using namespace std;

int main()
{
int MAX_ELEMENTS = 5; //the maximum number of elements in the array

int arr[MAX_ELEMENTS]; //declares an array with a predefined number of


elements

int value; //value of each element of the array (is equal...)

write in the array

for (int i = 0; i < MAX_ELEMENTS; i++)


{
cout << "Enter the value to be assigned to element " << i << " of
;
cin >> value;

arr[i] = value; //will iterate over the array from 0 to MAX_ELEMENTS


}

read in the array

for (int a = 0; a < MAX_ELEMENTS; a++)


{
array[a] = arr[a]
}

[Link]();
[Link]();

return 0;
}

Example 7.3 - Assigning values to array elements


The changes weren't that many: the arrangement of cout and cin just moved inside the
I also created another loop for the user to be able to see the results, following the same principle.
[Link]

of writing.

Working with characters - Introduction


So far we have only used the int variable type. I will teach you how to work with characters.
(using the char variable type), which is used if we want to store the character's name,
for example. I didn't talk about the char type because if we do: char name; the name can only
store 1 character. With the study of arrays, we can then store a name. For example:
char name[6] = "Agnor";
This would create an array of 6 char type variables. Did you notice we declared 6 variables in the array?
but Agnor has only 5 letters. This is because all strings (arrays of characters) are mandatory
they end with the "terminator character" ('\0').
See this basic example:
#include <iostream>
using namespace std;

int main()
{
int MAX_CHARS = 30;
char name[MAX_CHARS];

Please enter your name:


cin >> name;

Hello,

[Link]();
[Link]();
return 0;
}

Example 7.4 - Welcome Message


As you see, your name cannot have more than 29 characters in this example, but you can expand it.
will (as long as they don't exaggerate, since each character takes up 1 byte).

Two-dimensional arrays
Two-dimensional arrays are widely used in maps...
Vamos dar o exemplo de um mapa da Batalha Naval:
0 1 2 3 4 5 6 7 8
0 0 5 5 5 5 5 0 0 0
1 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0
3 0 0 0 0 4 0 0 0 0
4 0 0 0 0 3 0 3 3 3
5 2 2 0 0 4 0 0 0 0
6 0 0 0 0 4 0 0 0 0
[Link]

Legend:
0 - Water
2 - Ship that occupies 2 spaces
3 - Ship that occupies 3 places
4 - Ship that occupies 4 spaces
5 - Ship that occupies 5 spaces
To pass this into a normal array... it was complicated, but a two-dimensional array is
reasonably easy:
int mapa[7][9];
Then we just had to do mapa[0][0] = 0; mapa[0][1] = 2; etc...
Fortunately, there is a simpler method to load maps, using the for operator and reading
files. This will be explored in future lessons.
End of class 07 of C++:
Next classC++ 08 - Reading and Writing in Text Files - Introduction
Download thesource codetwo examples from the class
Download the class in PDF (Coming Soon)

Go to the top of the page

Class 08 - Writing and Reading in Files - Introduction


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-fstream, standard C++ library for reading and writing to files


-ofstream, for writing to files
-ifstream, for reading files
getline(), function to receive a line from the user ([Link]) or from a file
(ifstream::getline)

Writing and Reading in Files


The reading (and writing) of files has become essential in game programming, for example in
construction of maps and to store the player's path in the game.
During this lesson we will focus on the basics of writing and reading in files. The loading
data maps and data processing will come later.
[Link]

In order to have access to reading (or writing) files, we will need to use the fstream library.
The best way to explain the basics of writing/reading in files is with a
program:
#include <iostream>
#include <fstream> //includes the fstream library, to use ofstream and
ifstream
using namespace std;

int main()
{
// to write, the instruction is ofstream variable("file_name.txt")
ofstream doc_out("[Link]"); // opens the file [Link] for writing

// for reading the instruction is ifstream variable("file_name.txt")


ifstream doc_in("[Link]"); //opens the file [Link] for reading

char aux[50]; // creates an array with capacity for 50 characters

doc_out << "Nivel:1\n" << "Nick:Agnor" << endl;

doc_out.close(); //don't forget to close the output files!!!!

while (doc_in >> aux) //while the content of the document is not transferred
for the aux...
{
cout << aux << endl; //...prints the words on the screen.
}

note that the read file does not need to be closed

[Link]();
return 0;
}

Example 8.1 - Writing and Reading in a text file


Let's go step by step:

ofstream
ofstream means output file stream, it is used for writing to files. Before you can write
we have to define in which file we want to save the text: ofstream
variable_name(file_name). Both oofstream and ifstream belong to the library
fstream, which must be included in the program (#include <fstream>). It should be noted that all the
written files need to be closed when we no longer need them (using the
close() ).

ifstream
ifstream serves for reading files (input file stream). It is defined as the ofstream library:
ifstream variable_name(file_name)
Tip:
[Link]

To access a text file that is inside a folder, we need to separate the folder name.
of the filename, through a '/'. For example: ofstream map("maps/[Link]");

doc_out << string; e doc_in >> string;


We send text to a file in the same way we send it to the console output and read a
file in the same way we read it through the console input. In this example:
doc_out << "Level:1" <<- we are sending the string "Level:1" and the command endl (to change to
line) to the doc_out, that is, to the file identified by doc_out ([Link]).
doc_in >> aux- we are sending the content of doc_in (only the first word) to the string
aux.

doc_out.close()
Whenever we finish writing to the file, we have to close it. To do this, there is the close() function.
within the fstream library. Note that a '.' (dot) is used to connect doc_out to the 'function'
close(). This will be explained when we talk about classes.

while (doc_in >> aux)


Since when we do doc_in >> aux only the first word is transferred to the output, we have to create
a loop. The expression (doc_in >> aux) will be true when it reaches the end of the file. So,
as long as it does not reach the end of the file, doc_in >> aux will be executed and it will be shown in nocouto
content of aux. As every time we do doc_in >> aux this moves to the next word, it is
showed the entire content of the file, word by word.

Use [Link]()
The use of [Link]() may seem completely off topic for the lesson, but you will understand later.
why did I put it here.
So far, you must have noticed that in a program that receives data from the user through input.
They will only receive a word and not a sentence. [Link](), as the name itself
indicates, receives a line from the user. The function prototype is:
[Link](char *buffer, int length, char terminal_char);

Ochar *bufferserá astring(character set) where the input will be stored, alenght will be the
the size of the string, the last will be the terminating character. The terminating character is predefined.
that is, when the sentence ends.
You should note that there is an asterisk (*) before the buffer variable. This is a declaration of a
pointer (which will be explored in theclass 11The use of pointers (char* buffer) allows us to create
a string, without the need to define a specific number of characters
The last parameter is optional, and in most cases it can be ignored. Here is an example.
for use with the function:
#include <iostream>
using namespace std;

int main()
{
char name[150]; //creates a variable capable of containing 150 characters
[Link]

Enter your full name:


[Link](name, 150);

Your name is:

[Link]();
return 0;
}

Example 8.2 - Use of [Link]()


Deve ser o suficiente para perceberem, no entanto qualquer dúvida e contact me.

Read lines from files


To read lines in files, the function is exactly the same, only applied differently.
For example:
ifstream doc_in("[Link]");
doc_in.getline(variable, 200);
Difficult? Not at all :P
Whenever we use the getline() function, the file advances to the next line (instead of advancing
for the next word). Try the code below:
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
char aux[150]; // creates a variable capable of holding 150 characters, for the
writing
char welcome_message[150];
char name[150];
char age[4]; //only contains 4 characters, not needed more for the age
note that it is of type char and not int... a problem to be explored in classes
more advanced

ifstream doc_in("[Link]");
ofstream doc_out("[Link]");

Welcome to the Program


it can be customized
by the user, but only by
programmer
cout << "Enter your name: " << endl;
[Link](aux, 150);

doc_out << aux << endl;

cout << "Enter your age: " << endl;


cin >> aux;

doc_out << aux << endl;

doc_out.close(); //closes the document


[Link]

doc_in.getline(welcome, 150); //every time it calls the function


line change
doc_in.getline(name, 150);
doc_in.getline(age, 4);

cout << welcome << " " << name << ", " << age << " years" << endl;

system("PAUSE");
return 0;
}

Example 8.3 - Welcome Message 2.0


It does not require much explanation. There are some problems with this code that prevent it from being
a viable way to save games, but will be explored (and resolved hopefully :) in future lessons.
A good exercise would be to separate the program, creating a version that would serve only to create the
a text file, and another to read it, would be a quite primitive version of a level editor.
End of class 08 of C++:
Next classC++ 09 - Reading and Writing in Text Files - Introduction
Download thesource codetwo examples from the class
Download the class in PDF (Briefly)

Go to the top of the page

Aula 09 - Enumerações e Estruturas


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

enumerations, as a way to assign a logical meaning to the code


-structures, like a set of properties of a variable

Enumerations
Enumerations help to make code more logical. Let's imagine that we have a
function that receives the parameter:

int cor;
[Link]

We decided, to represent colors in integer numbers, to convention the value of blue as 1, that of
red as 2 and green as 3. Thus, to represent the color blue we would do something like:
cor = 1;
We would then have to memorize a table with the colors, or always carry one when
we program... Fortunately, there are enumerations:
#include <iostream>
using namespace std;

enum CORES { AZUL = 1, VERMELHO = 2, VERDE = 3 };


Don't forget the braces, NOR THE SEMICOLON

int CheckColor(COLORS color_to_check); //function to check which color

int main()
{
CORES cor; //look! CORES is a type of variable

cor = AZUL;

CheckColor(color);

cor = VERMELHO;

VerifyColor(color);

CheckColor(GREEN);

cout << BLUE << " " << RED << " " << GREEN << " " << color << endl;

[Link]();
return 0;
}

int CheckColor(COLORS color_to_check)


{
if (color_to_see == BLUE)
{
The color you chose was Blue
}

else if (cor_a_ver == RED)


{
The color you chose was Red
}

else if (cor_a_ver == GREEN)


{
The color you chose was Green
}
}

Exemplo 9.1 - Enumerações: Cores


I think it's easy to understand, after all, enumerations exist to simplify writing (and later
reading) of the code.
[Link]

It only remains to say that an enumeration is a constant variable, that is, the value of BLUE,
RED and GREEN cannot be changed.
Don't forget that if you do cout << BLUE; it will show '1' and not "BLUE", but that's
obvious...
Tip:

In the example above we did:

enum CORES { AZUL = 1, VERMELHO = 2, VERDE = 3 };

But we could have done:

enum CORES { AZUL = 1, VERMELHO, VERDE};

It does exactly the same effect, as it is enough to assign a value to one variable, so the others are
incremented ( += 1)
We could also do:

enum CORES { AZUL, VERMELHO, VERDE};

But this time BLUE would be equal to 0 and not 1.

Use of enumerations in games


Within game programming, there are various uses for enumerations. For example, it is common
use enumerations to represent the keyboard, since in some libraries, the key value
pressed by the user is expressed in numbers (in some cases in hexadecimal). Thus:
enum Keys
{ ... KEY_LEFT = 112, KEY_RIGHT = 113, ... };

Keys t;
if(t == KEY_LEFT)
{ moverNaveEsquerda(); }
The values are invented, but something similar is processed in the games. Instead of doing if(t ==
112) we can do if(t == KEY_LEFT) which is much simpler.
Another use for enumerations within games is in the game cycle. Various states are created.
(RUN, STOPPED, NEW_GAME, GAME_MENU, for example) and whenever we want
to switch from one state to another, it would be enough to modify the variable that holds the values. We will see this
but later, when we create the first 2D game.

Structures
A structure can be considered as a framework of the properties of a certain
variable. Let's imagine that we have 3 characters in a game: Nillight, Laveiuse, Nysker. Each
the character has the following variables: int hp(Health Points= Health Points), int mp(Magic
Points = Magic Points) and
We will then create a structure called Character:
#include <iostream>
[Link]

using namespace std;

struct Character
{
int hp, mp; //podem fazer isto; explicação abaixo.

; //Look at the semicolon; !!!!!!!!

int main()
{
different ways to fill the variables:
Personagem Nillight = { 30, //HP
10, //MP
};
Personagem Laveius = { 50, 7 };

Nysker character;

[Link] = 20; //you can do this


[Link] = 60;

HP of Nillight is
[Link] << endl;
HP of Laveius is
<< endl;
HP of Nysker is
endl;

[Link]();
return 0;
}

Example 9.2 - Character Structure


A structure is defined as follows:
struct name_of_structure {
//...variables
};
Notice:

Never forget the ';' after closing the brackets '{}'.


To access the variables that are within the structure, we use a dot to separate them.
"structured" variable and the property:
Test character;
[Link] = 0;
cout << [Link];
We can create structures for practically everything. In the following example, I will represent a
structure of a square (geometric figure):
#include <iostream>
using namespace std;

struct Square
{
[Link]

int side;
int area;
};

int calculateArea(Square square)


{
return ([Link] * [Link]);
}

int main()
{
Square square;
[Link] = 4;

[Link] = calcularArea(square);

cout << "Area of the Square: " << [Link] << endl;

[Link]();
return 0;
}

Example 9.3 - Square Structure - Show the area of a square


For homework, you can create functions to easily change or show various attributes.
Thus, the prototype of the function to view a character's HP would be:

int getHP(Character character);

And to modify the value it would be:

void setHP(int hp, Character character);

Game - Hall of Monsters


It's a simple game, created by me, based on text mode adventures (MUD style).
it is said that it is a summary of the classes so far:
/*
Example 9.4 - Hall of Monsters
Property of [Link]
*
* Autor : João Portela aka Agnor
* Data : 20/02/2004 a 21/02/2004
* Desc : Hall of Monsters - jogo-tutorial
*
*/

#include <iostream>
#include <windows.h> //to use GetTickCount();
using namespace std;

/************************************
**************STRUCTURES*************
************************************/
[Link]

struct Character
{
int hp; //the hit points
int mp; //Mana Points
int max_hp; // will be used to recover the character at the end of each
departure
int max_mp; // as mentioned above.....
int strength; // the character's strength
};

struct Monster
{

int hp; // Monster HP


int strength; //monster's strength
Monsters do not need MP.
char *name; // necessary so we can change the value of the name anytime
whatever we want...
It will be explained in class 11 - references and pointers
};

/////////////////////////////////////
///////////Variables/////////////////
/////////////////////////////////////

Personagem player = {50, 7, 50, 7, 5};


Monstro ORC = { 40, 10, "Orc" };
Monstro LIZARD = { 60, 15, "Lizard" };
Monstro SHADOW = { 100, 23, "Shadow" };
Monstro BAHAMUT = { 140, 31, "Bahamut" };
Monstro ULTIMA = { 1000, 100, "Ultima" }; // tentem matar este :P

/* *
Function declarations
* */

int gameMenu();
int callBattle(Monster monster);
int menuBatalha(Monstro monstro);
int MonsterAI(Monster monster);
int won();
int lost();
int getRandom(int from, int to);

What a small hand it is, right?

int main()
{

gameMenu();

[Link]();
return 0;
}

callBattle(monster);
Call a Battle for a specific monster (e.g., callBattle(SHADOW);
)
*/
[Link]

int chamarBatalha (Monstro monstro)


{
A
battleMenu(monster);
return 0;
}

/* Creates the Battle menu (used by calling chamarBatalha(monster); */


*/

int battleMenu (Monster monster)


{
int choice;
Your HP:
Your MP:
cout << "Choose an attack:" << endl;
1 - Normal attack
2 - Fire
cin >> choice;

switch (choice) {

case 1:
[Link] -= [Link] * 7;
cout << "\nVoce atacou!" << endl;
break;

case 2:
[Link] -= [Link] * 10;

[Link] -= 7;
You used the fire!
break;

default:
Unknown command...
battleMenu(monster);
We are using recursion in the functions: the menu will be
called again
break;
}

if ( [Link] <= 0 )
won(); //if there is only one instruction, an if does not need to have
chavetas { ... }
else
MonstroIA(monstro);
return 0;
}

The artificial intelligence of the Monster. To give players more options.


Only 25% of the Monster can use the special attack

int MonstroAI(Monster monster)


{
int random;
random = getRandom(1, 4);
switch (random)
[Link]

{
case 1:
case 2:
case 3:

[Link] -= [Link];
break;
case 4:

special
[Link] -= [Link] * 2;
break;
}

if ([Link] <= 0)
lost();

else
menuBatalha(monstro);

return 0;
}

//a popular function getRandom

int getRandom(int from, int to) {

srand(GetTickCount());
int random = ( rand() % ate ) + de;
return random;
}

lost :(((((

int lost()
{
You lost... Next time you will have better luck :(
gameMenu();
return 0;
}

//won... and also leveled up :PPPP

int won()
{
Wee won!!!!! and leveled up :P
[Link] += 2; //the modifications to "level up"
player.max_hp += 10;
player.max_mp += 7;
[Link] = player.max_hp; //recover energy
[Link] = player.max_mp;

wait.....
[Link]();

gameMenu();

return 0;
[Link]

the game menu

int gameMenu()
{
int choice;

Choose an opponent:
1 - Orc
2 - Lizard
3 - Shadow
4 - Bahamut
5 - LAST

cin >> choice;

switch (choice)
{
case 1:
chamarBatalha(ORC);
break;
case 2:
callBattle(LIZARD);
break;
case 3:
callBattle(SHADOW);
break;
case 4:
callBattle(BAHAMUT);
break;
case 5:
callBattle(LAST);
break;
default:
Command not recognized.... try again
<< endl;
gameMenu();
break;
}

return 0;
}

Example 9.4 - Hall of Monsters


It is a quite simple game and has some bugs (logical errors), but it demonstrates everything that
we learn.
Let's experiment with modifying the program, adding more monsters, fixing bugs,
adding attacks.
They can use the emailrpgplus@[Link] to send me the game to fix (and maybe publish
the site has the modifications :)

End of class 09 of C++:


Next classC++ 10 - Scope and LifetimeVavariables
[Link]

Download thesource codetwo examples from the class


Download the class in PDF (Coming soon)

Go to the top of the page

Class 10 - Scope and Lifetime of Variables


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

global variable, a variable that can be accessed in all blocks of the program
-local variable, a variable that can only be accessed in the block in which it was declared
-scope resolution operator (::), operator to access global variables that have the
same identifier of a local variable
lifetime of a variable, the period of time in which a certain variable exists
stored in memory
-static variables, variables that, although local (from a scope perspective), possess the
same lifespan as a global variable

Declaration of global and local variables


If you have ever tried to create a program, you have surely encountered various errors.
compilation. Certainly, some were due to distraction, but others may have been caused by
the simple fact of declaring a variable locally, instead of declaring it globally. If you
it happened, in part it was my fault, for not having explained this sooner (although I did give
a brief introduction toclass 06), that's why this lesson is dedicated to explaining this concept.
First of all, a global variable is a variable that can be used throughout the program.
A local variable can only be used in the block or function where it was declared.
In order to declare a global variable, we will have to declare it outside the definition of a
function or a block. To have a local variable we must declare the variable inside the
definition of a function or a block. Here is an example:
#include <iostream>
using namespace std;

int func();

int x = 100; //global variable, so it can be used throughout the program

int main()
{
[Link]

int y = 2; //local variable, can only be used in the main() function

return 0;
}

int func()
{
int z = 10; //local variable, can only be used in the function func()
return x;
}

Example 10.1 - Global variables vs local variables


Acho que já perceberam como se define uma variável global e uma variável local. Notem também
the arguments of a function are local to it.

Global and local variables in a program


To get a practical idea of the various mistakes we can make, take a look at this entire program.
commented:
#include <iostream>
using namespace std;

int i = 20; // global variable, used throughout the program

void function();

int main()
{

int x; // declare an integer variable


i = 30; // correct, because i is a global variable!

function();

y = 20; //error!!! y was only declared inside the function() so it is not


accessible within main()
x = 10; //correct, since x belongs to the main function
i = 20; //correct

for (int a = 1; a < 10; a++)


//start of block
a = 2; //careful this is an infinite loop, since a never goes beyond 2, right?
Arriving, therefore, at 10!!!!!
} //fim do bloco

a = 30; //wrong!!! a can only be accessed inside the for loop

[Link]();
return 0;
}

void function()
{
int y; //declare a variable inside the function();
[Link]

x = 30; //wrong! x is not declared in this function();


y = 10; //correct
i = 5; //correct. i is a global variable;

Non-compilable example
PS: Don't even try to compile this program, as it is full of errors :D
Tip:

Some compilers consider the instruction as a separate case, that is, they consider that if a
The variable defined within the do-for block will belong to the function where it is.
contained, instead of belonging only to the block:

for (int a = 0; a < 10; a++)


{ cout << a; }
a = 2 //in some compilers this would give an error, in others everything would be fine....

All the theory described above is applied in this example.

Scope resolution operator (::)


Seethefollowingexample:
#include <iostream>
using namespace std;

int x, y;
void moveRight(int x);

int main()
{
x = 20;
moveRight(15);
cout << x << endl;
[Link]();
return 0;
}

void moveRight(int x)
{
::x += x; // the global variable x += the local variable x
}

Example 10.2 - Using the scope resolution operator ::


In this way, we can use global variables, even if there are local variables with the same name.
name inside the function.

Memory and Lifespan


Imagine memory as a sequence of bytes. Each byte has 2 types of values: one
[Link]

number (or the value we assign) and an address.


When we create a variable, we are placing, at a certain memory address, a
value.

Let's imagine that we are looking at the computer's memory (from address 93 to 107):

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107


Now if we wrote in C++:
int x = 70;
We would be writing something in memory like:

70
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
PS: The table does not fully represent reality, as each int occupies 4 bytes (it should have been written
in binary and not in decimal), but I think they got the idea....
This served to help you try to visualize what computer memory is.
As you may know, the memory we have available on the computer is limited and, therefore, in
larger programs, we will have to be careful to save as much memory as possible. The own
C++ does this in a simple way. Global variables will always be allocated in memory.
(until the program shuts down) while local variables will only be allocated in memory when the
function or the for block called will be eliminated when the function or block ends.

Static variables
See this example:
#include <iostream>
using namespace std;

int increment(); // function aimed at incrementing a value


int h; //global variable

int main()
{
for (int x = 0; x < 10; x++)
{
h = increment(); // increment the global variable h 10 times
}
cout << h << endl; //show the result
[Link]();
return 0;
}

int increment()
{
int h = 0; //creates a local variable
Note that there is no conflict with the global variable
//that has the same name.
h++; //increment
return h; //returns the result
}
[Link]

Example 10.3 - Increment function v0.1


The objective of the program was to obtain, in the end, the value of 10. However, we obtained the value of 1.
Why?
The answer is in the lifetime of the local variable. It is constructed and destroyed 10 times. Each
once it is destroyed, it loses any stored value, and each time it is built, it takes on the value
From 0. To remedy this, the best way is to build a static variable using the keyword static.
#include <iostream>
using namespace std;

int increment(); // function that aims to increment a value


int h; //global variable

int main()
{
for (int x = 0; x < 10; x++)
{
h = increment(); //increment the global variable h 10 times
}
cout << h << endl; //show the result
[Link]();
return 0;
}

int increment()
{
static int h = 0; //creates a static local variable
Note that there is no conflict with the global variable.
which has the same name.
h++; //increments
return h; //returns the result
}

Example 10.4 - Increment function v1.0


A static variable has the same lifespan as a global variable (it is initialized at the beginning of
program and destroyed at the end), but has the scope of a local variable (cannot be used outside
from the function where it was declared.

Notice:

We must always assign a value when declaring a static variable.


Tip:

If we declare a global variable without assigning a value, it will take the value 0.
If we declare a local variable without assigning it a value, it will acquire a random value.
End of class 10 of C++:
Next classC++ 11 - References and Pointers
Download thesource codetwo examples from the class
Download the class in PDF (Coming Soon)

Go to the top of the page


[Link]

Lesson 11 - References and Pointers


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-pointer, a variable that points to another variable, containing the address of it


-address, the location of a variable in memory. Think of it as if it were the address of a variable in.
computer
reference, the 'nickname' of a variable
- The address operator (&) is used to obtain the address of a variable.
operations with the value of variables pointed to by pointers, such as accessing the value of
another variable, through the use of pointers

Conceito de endereço e de valor - revisão


In the previous class (where I talked about memory), I already gave a brief explanation of address and value.
a variable. In this lesson, I will review the concepts, as to learn about pointers and references it is
much easier if you keep these concepts in mind. If we had a program running, the
memory would resemble something like:
Value
Address 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
If the program encountered a line of code like: int x = 25; the program would introduce the
value25 randomaddressnumber:
Value 25
Address 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177

Pointers - brief explanation


Pointers are a variable like any other, except that instead of containing values, they contain
variable addresses. Pointers are defined by an * (asterisk) before the variable
(int *pointer;)
There are several uses for pointers. In this lesson, I will only teach some basic operations with
pointers (notably with the value of the pointed variable).
Following is, for now, an explanation about references and the address operator (which will be)
important for use with pointers)
[Link]

Reference operator (&) and address operator (&)


If you read the title above, you must think that I am mistaken, for the two operators are
represented with the same symbol. It is not an error and both operators are indeed represented
by the same symbol (&) and the only way to distinguish one from the other is by context, but not
don't worry because, as you will see, it's very simple.
Let's start with the reference operator. When the symbol & is used when defining a variable.
this, instead of being a normal variable, will become a reference to another variable, that is,
it will be like a 'nickname' for this:
#include <iostream>
using namespace std;

int main()
{
int i;
int &i_ref = i;

i = 20;

cout << "Variable i: " << i << endl;


Reference for i:

i_ref = 10;

Variable i:
Reference for i:

[Link]();
return 0;
}

Example 11.1 - Using References


Note:

When we declare a reference, we have to immediately assign the variable we want to reference:

int &ref;
ref = i; // wrong!
---
int &ref = i; //correct!
As you can see from the program tantoicomoi_refpossuem the same values and, if we change the
the value of one of them will necessarily change to the same value. As you may have already
it is perceived that there are not many advantages in using references in this case, but if we use them
as arguments for functions, you will see their true utility:
#include <iostream>
using namespace std;

Swap Function
Swap the values of 2 integer variables

void swap(int &x, int &y); //we pass the arguments by reference
[Link]

int main()
{
int a = 20;
int b = 10;

cout << "A:" << a << endl;


cout << "B:" << b << endl;

swap(a, b);

A:
cout << "B:" << b << endl;

[Link]();
return 0;
}

void swap(int &x, int &y)


{
int temp; //temporary variable, so we don't lose the value of x
temp = x;
x = y;
y = temp;
}

Example 11.2 - Swap Function


In summary, so that we can change the 2 values simultaneously (without using global variables)
we use references. We could use global variables for that, but with huge projects
we would have an enormous list of global variables.
Now I will discuss the use of the address operator.

Address operator (&)


The address operator (&) is used to obtain the address of a variable. Let's see the following
program:
#include <iostream>
using namespace std;

int main()
{
int var = 30;

cout << "Address of variable var: " << &var << endl;
cout << "Value of the variable var: " << var << endl;

[Link]();
return 0;
}

Example 11.3 - Using the address operator (&)


As you can see, if you run the program, you will get a strange number when we do
&var. This number is the address of the variable in memory and is expressed in a base
[Link]

hexadecimal (for example: 0x22ff31).


It is worth mentioning that if you want to store the address of a variable, you will have to store it through a
pointer. Like this:
int x = 10;
int v = &x; wrong
int *p = &x; correct

Pointer operations - introduction


To demonstrate an introduction to operations with pointers, the following is an example program:
#include <iostream>
using namespace std;

int main()
{
int x = 20;
int *pointer; // pointer to a variable of type int

pointer = &x; //the pointer takes the value of the address of the variable

cout << "Variable x:" << endl;


Value of x:
cout << "Address of x: " << &x << endl;

Pointer variable:
Value of pointer:
cout << "Pointer address: " << &pointer << endl;
cout << "Value of the variable pointed to by pointer (x): " << *pointer << endl;

[Link]();
return 0;
}

Example 11.4 - Obtain the memory properties of a variable and a pointer


Don't be alarmed for now with the amount of things you still don't know! While running the program
gave me the following output (which will be different from yours, since the address will not be)
even)
Output

Variablex:

Valor de x: 20
Address of x: 0x22ff74

Pointer variable:

Pointer value: 0x22ff74


Pointer address: 0x22ff70
Value of the variable pointed by pointer (x): 20
[Link]

To better understand, it is better to 'disassemble' the program:


Variable X:
Valor: 20
Address: 0x22ff74 (in this case)
Value 20 -- --
Address 0x22ff74 0x22ff75 ...
Pointer variable (the pointer to the variable x):
Value: 0x22ff74 (the value of a pointer is, then, the address of the variable it points to)
Address: 0x22ff70 (the pointer address. Note that it is 4 "positions" before whatX; this
it happens because a uint occupies 4 bytes
Valor da variável apontada por pointer (x):20
Value 0x22ff74 ... 20
Address 0x22ff70 ... 0x22ff74
As you see, it is important for us to test the examples ourselves, changing the values and
experimentando coisas novas, pois é com os erros que aprendemos.

Operations with pointers - operations with the value


There are two types of operations with pointers. In this lesson, I will only cover the operations with the value, since
what is the easiest to learn (and because this is already too long :).
In order to 'manipulate' the value of the variable pointed to by the pointer, we must use the
dereference operator (*)
#include <iostream>
using namespace std;

int main()
{
int x = 10;
int *pointer = &x;

cout << "Value of X: " << x << endl;


cout << "Value pointed by pointer: " << *pointer << endl;

x += 10;

Value of X:
cout << "Value pointed by pointer: " << *pointer << endl;

*pointer += 10;

Value of X:
cout << "Value pointed by pointer: " << *pointer << endl;

++*pointer; //or ++(*pointer) if you want

Value of X:
cout << "Value pointed by pointer: " << *pointer << endl;

[Link]();
[Link]

return 0;
}

Example 11.5 - Basic operations with the value of the variables pointed to by the pointers
Never forget to use the dereference operator whenever you want to work with the value.
Many of the mistakes that haunt programmers are due to the misuse of pointers, so
be very, very careful :) .
Now let's see how the swap function would look with pointers:
#include <iostream>
using namespace std;

// Swap Function -> use of pointers


Swaps the values of 2 integer variables

void swap(int *x, int *y); // we pass the arguments as pointers

int main()
{
int a = 20;
int b = 10;

cout << "A:" << a << endl;


cout << "B:" << b << endl;

swap(&a, &b); /* don't forget that we are using pointers, so


we have to use the address operator to assign the
address of the variables to the pointers */

A:
cout << "B:" << b << endl;

[Link]();
return 0;
}

void swap(int *x, int *y)


{
int temp; //temporary variable, so we don't lose the value of x
temp = *x; //temp is equal to the value of the variable pointed to by x
*x = *y; //the value of the variable pointed to by x will be equal to the value of
//variable pointed by y
y = temp; //the value of the variable pointed to by y will be equal to the value of
temp
}

Example 11.6 - Swap Function (using pointers)

What is all this for?


If you have read all of this, you must be wondering what pointers are really for, because
there are references that, besides being much easier to use and understand, have
exactly the same effect. I do not blame you. There are several reasons:

1 - References are an evolution of the use of pointers. In C, references did not exist.
everything done through pointers (so far you are still right...)
[Link]

2 - The true utility of pointers in C++ (and believe me, they are really useful) lies with
dynamic memory and with operations with the address, something I chose not to provide in this lesson (for
lack of space and because it requires more knowledge.
3 - They had an excellent introduction to pointers. This knowledge of memory and
Pointers will be very important for understanding 100% the use of pointers.
End of class 11 of C++:
Next classC++ 12 - Character Handling
Download thesource codetwo examples from the class
Download the class in PDF (Coming Soon)

Go to the top of the page

Lesson 12 - Character Handling


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

character, a "symbol" (it can be a letter, punctuation marks, etc.) of type char
string, a set of characters (a word or a phrase, for example)
character arrays, a set of characters, thus a string
Pointers to strings point to sets of characters, so it is not necessary to size them.
the pointer
-class string, standard library of C++, which aims to assist in manipulation of
strings

Character handling in C
Since the introduction of C++, the class string started to be used for character handling.
However, since many programmers still use character arrays (that was what existed in C)
I thought it was important to teach at least the basics.

In C, a string can be defined through an array of characters (char type), which is logical,
since a string is a set of characters. I have already given an introduction about this in thelesson 7,
That's why I think it's better to take a look at how to define a character array.
Like any array, we can change the present values as we wish.
#include <iostream>
using namespace std;
[Link]

int main()
{
char name[10] = "agnor"; // starts with 10 characters because there will be
necessary
later

cout << name << endl;


[Link]();

//vou mudar o nome para começar com letra maiúscula

name[0] = 'A'; //changes the first character (number 0) to the letter A

cout << name << endl;


[Link]();

I will add an s to the end of the name HQ

nome[5] = 's';
nome[6] = ' '; //espaço
nome[7] = 'H';
nome[8] = 'Q';

cout << name << endl;


[Link]();

return 0;
}

Example 12.1 - Change characters in a character array


Although it gives us a greater degree of control, it becomes unviable to use character arrays for
strings that are constantly changed. This can be solved by using pointers.
for characters:
#include <iostream>
using namespace std;

int main()
{
char *name = "agnor";

cout << name << endl;


[Link]();

nome = "Agnor";

cout << name << endl;


[Link]();

nome = "Agnor's HQ";

cout << name << endl;


[Link]();

return 0;
}
[Link]

Example 12.2 - Using pointers for strings


Os apontadores para caracteres tornam muito mais fácil esta tarefa.
Since it is a pointer, we cannot manipulate the source string, so we have a lesser.
control level, since we cannot change just one letter, we have to change the string
today. The pointer name is pointing to a location in memory that contains the string we created,
Agnor

Start a string without defining a value


To start a string, we don’t necessarily have to assign it a value right away. However, we have
to define the number of characters that the string has:
char string[50];
Agnor
We can also easily use pointers to characters:
char* string;
Agnor

Example 12.3 - Invert the characters of a word


#include <iostream>
using namespace std;

int main()
{
example

char dest[8]; //creates a variable with the same number of characters as the string

for (int j = 0; j < 7; j++)


{
dest[j] = string[6-j]; //copies the values from string to dest
inversely
}

dest[7] = '\0'; //don't forget to put the terminator

cout << "Initial string: " << string << endl;


Inverted string:

[Link]();

return 0;
}

Example 12.3 - Invert the characters of a word


The first lines of code are easy to understand. We create an initial string (string) and a
string that will be inverted (dest). Both obviously have the same number of characters (not
forget the terminating character).
Then we created a condition for which string will be copied in reverse:
[Link]

Program:

dest[0] = string[6] //character 'o'


dest[1] = string[5] //caracter 'l'
dest[2] = string[4] //character 'p'
dest[3] = string[3] //character 'm'
dest[4] = string[2] //character 'e'
dest[5] = string[1] //caracter 'x'
dest[6] = string[0] //character 'e'
Then we insert the terminator character () at the end of the array and display the result on the screen.
Simple!
Now I decided to complicate things a bit so we can have much greater control over the program:
#include <iostream>
using namespace std;

int main()
{
example

int n = sizeof(string) - 1; //n is the number of characters in the string variable,


removing the terminating character \0

char dest[n+1]; // creates a variable with the same number of characters as


string

for (int j = 0; j < n; j++)


{
dest[j] = string[n-j-1]; //copies the values from string to dest
inversely
//without obviously copying the terminating character
}

dest[n] = '\0'; //do not forget to put the terminator

cout << "Initial string: " << string << endl;


cout << "Reversed string: " << dest << endl;

[Link]();

return 0;
}

Example 12.4 - Invert the characters of a word (version 2.0)


Basicamente todos os principios foram explicados no programa anterior a [Link] só explicar a
sizeof function.
Basicamente a função sizeof diz-nos o número de bytes ocupados por uma variável. Se fizessemos
sizeof(n) the result would be 4 (the int type occupies 4 bytes). Since each char occupies 1 byte and we have a
array with 8 variables of type char (one for each character + one for the terminating character)
will occupy 8 bytes.
With this program, we will now be able to freely change the initial string without needing to modify it.
anything else in the program.
[Link]

Strings in C++
As C++ is an evolution of C, it is natural that C++ has an easier way of manipulation.
strings.
In C (as we can see above), manipulating strings is somewhat of a hassle for the programmer (having to
even if creating some functions to help you). In C++, a class was created that makes life easier
of the programmer: the class string.

String Class
In order to access the string class, we must first include it in the program in the same way.
that we include the iostream class:
#include <string>
Another important thing is that what this class does is provide the programmer with a simple and powerful way
to manipulate strings without "getting your hands dirty" in unnecessary code. See the following
program:
#include <iostream>
#include <string>
using namespace std;

int main()
{
string String1; //we initialize a string without assigning a value
Note that we do not have to assign any size.

Welcome to the world of Strings in C++


start
//as strings
in this way
Agnor's HQ
string String4(String3); //we can easily start a string with
another string

cout << "String2: " << String2 << endl;


String3: String3
cout << "String4: " << String4 << endl;

String1 = String3; //look! It is not even necessary to resize the array...


String3 = String2; //everything is done by the string class

String1:
cout << "String2: " << String2 << endl;
cout << "String3: " << String3 << endl;
String4: String4

[Link]();

return 0;
}

Example 12.5 - Using the string class


It may seem a bit confusing the different ways of initialization and, therefore, I don't want to get into it.
in more detail about the String class, without mentioning classes first (next lesson).
[Link]

To finish, I will just show that we can access only one character (which is exactly the same
thing that in C) with a program that shows each letter of a string:
#include <iostream>
#include <string>
using namespace std;

int main()
{
String String("Agnor");

for (int j = 0; j < 5; j++) //shows each letter sequentially


{
cout << j+1 << "the letter: " << String[j] << endl;
}

[Link]();
return 0;
}

Example 12.6 - Display one letter at a time with the string class

Final example - Guess the word game


The following game is based on Hangman. The player has unlimited attempts to guess the word.
chosen by the player. Contains some things that they should not understand yet ( [Link]() and
[Link](), for example), but which will be addressed later. Enjoy the game:
/********************************
Game: Guess the word
Autor: João Portela a.k.a. Agnor

[Link]
*********************************/

// Includes of the program

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;

Function declaration

returns the number of characters in a string


//Example: int x = size("hello");
int size(string str);

Check if the letter at the index position of the two strings are
equals
//Example: bool test = checkLetter("table", "house", 2);
bool verifyLetter(string attempt, string source, int index);

Verifies if the two strings are equal


//Example: bool test = checkWord("table", "house");
bool verifyWord(string attempt, string source);

Returns a random number between [from] and [to]


Example: int x = getRandom(0, 3);
[Link]

int getRandom(int from, int to);

Shows the game menu and returns the chosen option


//Example: int option = menu();
int menu();

shows the winning message


//Example: won();
void won();

The game's logic itself. Source is the string that contains


the word 'winner' and discoveries is the string that says
Which letters are correct. Returns true if the player
hit the string (source)
//Example: bool won = game_logic("cat", discoveries);
bool game_logic(string source, string &discoveries);

//Desc: cria um novo jogo


//Example: new_game();
void new_game();

int main()
{
bool done = false;

while (!done) //starts a game loop. Exits only when done is


equal to true
{
cout << "Welcome to the game: GUESS THE WORD" << endl;
This game is a modification of the Hangman game
Created by Joao Portela aka Agnor
[Link]

int choice_menu = menu(); // choice_menu will take on the


value
chosen by the user

switch (menu_choice)
{
case 1:
new_game(); //a new game starts
break;
case 2:
done = true; //exit the game loop
}
}

Thank you for playing this game.

[Link]();
return 0;
}

Function Definition

int size(string str)


{
return (int)[Link](); //returns the number of characters in a string
(I will explain later)
[Link]

bool checkLetter(string attempt, string source, int index)


{
if (attempt[index] == source[index]) //if the letters are equal, then
same index...
{
return true; //when returning, exits the function
}

return false;
}

bool verifyWord(string attempt, string source)


{
if (attempt == source) //if the strings are equal...
{
return true;
}

return false;
}

int getRandom(int from, int to)


{
int random;
ate -= de;
random = rand() % (ate + 1) + de;
return random;
}

int menu()
{
int choice;

Choose an option:
1 - New Game
cout << "2 - Exit\n" << endl;

cin >> choice;

return choice;
}

void won()
{
Congratulations! You won the game!
[Link]();
[Link]();
}

bool game_logic(string source, string &discoveries)


{
string attempt;

The word chosen by the game has


letters
Letters already discovered:
Enter your attempt:
[Link]

cin >> attempt;

if (size(source) != size(attempt)) //just to ensure they have the


same number of characters
{
Does not have the same number of letters!
[Link]();
return false;
}

if (checkWord(attempt, source))
{
return true;
}

else
{
for (int i = 0; i < size(source); i++) // traverses all the
letters of the string
{
if (checkLetter(attempt, source, i)) //if the letters are
equal
{
discoveries[i] = source[i]; //equal the discoveries
}

else
{
discoveries[i] = '-'; // this character gets the value '-'

//for it has not yet been discovered


}
}
}

return false;
}

void new_game()
{
srand(GetTickCount());

string source[10]; //creates an array of strings, a kind of collection of


words

source[0] = "casa"; //algumas palavras...


table
source[2] = "rato";
source[3] = "manteiga";
source[4] = "luar";
key
manto
song
source[8] = "rio";
school

string discoveries; //the characters that have been discovered by the user
[Link]

int indice = getRandom(0,9); //choose the position of the word in the list
above

for (int x = 0; x < size(source[index]); x++)


{
[Link](size(source[index]));
makes discoveries the same size as source, for
in case there is
//to allow us to change the characters below (will be explained
after)

descobertas[x] = '-'; //põe todas as letras com o símbolo '-'


(not discovered)
}

bool win = false;

while (!vencer) //as long as not win...


{
vencer = logica_jogo(source[indice], descobertas);
}

won(); //shows the winner message


}

Exemplo 12.7 - Jogo ADIVINHAAPALAVRA


There are some concepts that I haven't used that often throughout the lessons:

bool game_logic(string source, string &discoveries);


In the function's arguments, we used a reference to a string, so that we can not only access
to the value of discoveries, but also for the power to change. This way we avoid the use of a variable
global.

return (int)[Link]();
This requires a greater dose of explanation.
Think that str is any object (in this case it is a word). When we use the '.' (dot), we are
to access the attributes of that object. Thus, we are accessing the size() attribute of the string object.
This is one of the concepts of Object-Oriented Programming that we will cover in the next class.
Just know that this allows us to obtain the number of characters in a string.
Another thing that also captures our attention, the(int):
The function size() (which is inside the str object) returns a value of type size_t, a value that the
C++ standards define it as a specific value for size (number of characters) of
strings. In fact, the "heart" of this type of variable is an unsigned int, that is, an integer with
only positive numbers. Since it only presents positive numbers, it has double the capacity of a uint.
normal. As such, if we try to convert a size_t to an int, the compiler will give us a warning:
Possible data loss. This is because, if the number of characters is in the order of billions, the type
it may not support it. But as we know that this is impossible (no string that we will
[Link]

to make will have this number of characters), when we use (int) it is our way of telling the
compiler that we do not mind that size_t is converted to int, and the compiler already does not
it's going to annoy us.

[Link](size(source[index]));
Inside the discoveries object, we have a function called resize, which serves the purpose of preparing the
string for a certain number of characters. Strings may seem "magical", but doing the
the following code would be wrong:
string str = "hello"; //three characters str[3] = 'b'; //wrong, because
there are only 3 characters in the string!

And the correct form:


string str = "hello"; //three characters [Link](4); str[3] = 'b';

Use of apostrophes ' instead of quotes "


You probably noticed that I used '-' instead of '-'. This is because when we use '-', we are defining
a whole string, not just a character. Doing char p = "a"; would give an error. The correct way, when
we want to use only one character, char p = 'a';
End of lesson 12 of C++:
Next classC++ 13 - Classes - Part I
Download thesource codetwo examples from the class
Download the class in PDF (Coming soon)

Go to the top of the page

Classroom 13 - Classes - Part I


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

procedural programming, a style of programming based on steps/stages, as if it were


from a cookbook
object-oriented programming, a style of programming where the programmer creates objects,
abstracting from the code, based on real-life examples. Each object can (and should)
interact with each other.
-class and object, an object belongs to a certain class. In the example, Chair
[Link]

office_chair; Chair would be the class and office_chair the object.


Accessibility points to character sets, without the need to size the pointer.

Programming paradigms
So far we have been programming using a procedural programming style, that is, a style
of programming that uses several functions (several steps or instructions) to be executed. By
example:
1st - Pick up the phone;
2nd - Mark the number;
3rd - Wait for some activity from the phone;
3.1 - If someone answers, jump to step 4;
3.2 - If the signal is interrupted, turn off the phone, wait 1 minute, and return to step 1;
3.3 - If it doesn't answer, hang up the phone, wait 30 minutes, and go back to step 1;
Speak and have a pleasant conversation;
5 - Turn off the phone;
In C++ this code (using functions and the procedural paradigm) could look like this:
callPhone(home_phone);
markNumber(home_phone, number);
int signal = phone_signal();

while(sinal == 0)
{
wait(wait_time);
}

while (signal != 1)
{
case 2:
//....
}

speak();
turn_off_phone(home_phone);

One of the weakest points of the C language (the predecessor to C++) was its lack of support for
the call Object Oriented Programming (OOP - Object Oriented Programming).
The C++ language, besides supporting the OOP paradigm and the procedural one, supports two others.
(Abstract Data TypeeGeneric Programming). This is a huge advantage, since
we can choose to program in 4 different ways! So far I have taught you
procedural programming, but from now on it is better to get used to Programming
Object-oriented, since it is the paradigm that "is in vogue" (the languages of the new
generation like Java and C# "force" the programmer to use it.
After this 'rain' of technical terms, let's go to Object-Oriented Programming.

Object-Oriented Programming (OOP) - Introduction


In OOP, instead of the program being a list of instructions (steps) to follow, it becomes a
set of objects, capable of interacting with each other, sending, receiving, and processing messages.
With a 'real-life' example, you will see that the concept is very simple and very interesting.
[Link]

Let's imagine an object, for example, a human (object is not in that sense).
First of all, a human is made up of several organs. It has a mouth, a nose, two
eyes, etc.
A human being is a mammal. This means that it shares several characteristics with all the
mammals, for example, have a heart, spine, hair, in addition to having the same functions
basic: to mate, to feed, to sleep, etc.
Furthermore, a human being has several functions, such as speaking, reading, writing, etc.
We can then construct the following diagram:

Note:

The diagram above is drawn following the UML (Unified Modeling Language) 'language'.
It is a "language" to expose the relationship between the classes of a program and is fundamental.
when we are planning the code for a large project (a game, for example) and when
We are working in a team with more programmers.

For now, since the programs we will be making will be very simple, it is not necessary for us to
plan it through diagrams.

Perhaps I will go into more detail about this language in future classes.
Well, now that we have learned the concept of object-oriented programming, let's see its use.
in a real program.

Classes
Nalesson no. 9I explained how to use structures (struct).
Classes are an evolution of structures (they only have one significant difference), in C they were used
Structures, in C++, due to the introduction of the OOP paradigm, use classes.
So why did I teach structures first? Firstly, because using structures is a bit
easier for beginners. Second, because there are still many programmers who use classes and
structures in the same program (including myself), so they are already prepared for everything.
[Link]

Note:

The truth is that structures shouldn't even exist in C++. They exist only to maintain the
compatibility with the C language.
Classes are defined using the keyword class and follow practically the same rules as
the structures. An example of a simple class is:
class Point
{
int x, y;
};

It's very similar to a structure, but it is different from:


struct Point
{
int x, y;
};

So where is the difference?

Accessibility
The difference between classes and structures lies in their accessibility. In a class (or in a structure), the
members can be declared as public or private.
Private members can only be accessed by the class itself. Public members
they can be accessed both by the class and outside of it.
The default accessibility of a structure is public. Thus, in the example above, the variables x
they can be manipulated both inside and outside the structure.
The default accessibility of a class is private. Thus, in the example above, the
variables x and y can only be manipulated within the class.
Does it seem confusing? A simple example can clarify the doubts:
class Point
{
public

int x, y; //public members

private

int a, b; //private members


};

Which can also be defined by:


class Point
{
int a, b; //private members

public

int x, y; //public members


};
[Link]

Note:

In C++, there is another type of access called protected, but they do not need to
worry about him for now.

Methods
Methods are like functions that are contained within a class. For example, imagine a
class Point (class that works with the Cartesian coordinates, x and y, of a point):
class Point
{
public
void changeX(int u_x); //changes the value of x
void alterY(int u_y); //changes the value of y
void change(int u_x, int u_y); //changes the value of x and y

int showX(); //returns the value of x


int mostrarY(); //returns the value of y

private

int x, y; //coordinates of the point


};

Note:

I named the attributes of the functions u_x and u_y to avoid conflicts with the variables.
private x and y.
The above functions (methods) are part of the class. Note that although the variables x and y are
private members can be accessed by the methods of the class itself.
Also note that we only declared the methods, we have not defined them yet. In order to define them
There are two ways. The first is to define them in the class definition:
class Point
{
public
void changeX(int u_x) { x = u_x; }
void changeY(int u_y) { y = u_y; }
void change(int u_x, int u_y) {
x = u_x;
y = u_y;
}

int showX() { return x; }


int showY() { return y; }

private

int x, y; //coordinates of the point


};

This method is quite easy, but it is not advisable for larger functions. The second method is
define them outside the class definition. In the following example, I will only define the method outside the class.
[Link]

change()
class Point
{
public
void changeX(int u_x) { x = u_x; }
void changeY(int u_y) { y = u_y; }
void change(int u_x, int u_y);

int showX() { return x; }


int displayY() { return y; }

private

int x, y; //coordinates of the point


};

void Point::change(int u_x, int u_y) {


x = u_x;
y = u_y;
}

As you can see, it is similar to defining a normal function, with one single difference: the inclusion
doPonto::. This instruction serves to inform the compiler that the following method belongs to the
class Point. The operator '::' is the scope resolution operator. It is used to tell the compiler
we want to access the function (method) 'alterar()', which is inside the class 'Ponto':
Point::change()

Classes vs Objects
At this point, it is important to understand the distinction between class and object. In the example below:
Seat Car
Body class or object. If we compare them to a variable, a class would be the
data type (int, char, etc.) and an object would be the variable itself.

Access class members


We can access the members of an object in the same way we access structures.
example,
ponto.x = 3;
cout << [Link]();

Final example and Accessibility Issues


To finish this part, an example program with all the "matter."
#include <iostream>
using namespace std;

class Point
{
public
void changeX(int u_x) { x = u_x; }
void changeY(int u_y) { y = u_y; }
[Link]

void change(int u_x, int u_y);

int showX() { return x; }


int showY() { return y; }

private

int x, y; //coordinates of the point


};

void Point::change(int u_x, int u_y) {


x = u_x;
y = u_y;
}

int main()
{
Point point; // we declare an object point of the Point class

//how to make point.x or point.y would give an error (private)....


[Link](3, 2);

//show the points:


cout << "X: " << [Link]() << "\nY: " << [Link]() << endl;

[Link](7);

//show the points:


X:

[Link]();
return 0;
}

Example 13.1 - Class Point


We could easily add more methods, such as summing, incrementing, etc.
You must be wondering why we declare variables as private, as it would be much more...
It's simpler to do point.x than [Link](). You can do it both ways, but it's preferable.
declare the variables privately and use one function to change them and another to get their value
value. This is because, if in the future you want to expand the functionalities of your class, it becomes
much easier. Imagine a classmonth. Do:

[Link] = 50;

It would obviously be a mistake, but when we create a method:

[Link](50);

We could ensure - within the method - that the variable would be less than 31 (if (day < 31)...).
This way we didn't have to change any code (we didn't have to put all the [Link] inside the function
main()), just a few lines inside the method changeDay().
End of class 13 of C++:
[Link]

Next classC++ 14 - Pointers - Part II


Download thesource codetwo examples from the class
Download the class in PDF (Coming soon)

Go to the top of the page

Class 14 - Pointers - Part II


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

dynamically allocated variable, a variable that is allocated in dynamic memory, whose size
can be changed
new creates a variable in dynamic memory and returns a pointer to it
-delete, deallocates the dynamic memory of the pointed dynamic variable
-With address operations, it is possible to access the next variable, very useful for arrays

Dynamic memory
So far we have hosted the variables and arrays statically. This means that when
we initialized a variable, it will always have the same size throughout the program.
In a normal variable, there is no problem, but in an array, this brings limitations. The first is
that we need to know the size of the array before starting the program. Another is that we cannot
change the size of the array according to our needs.
A solution to the first problem is to specify a maximum value for the array. However,
we will be wasting space in memory unnecessarily and nothing guarantees us that the space will be
sufficient (if not, prepare for constant errors during execution).
The only viable alternative is to allocate them dynamically. A dynamic variable can only be accessed
through a pointer, that is, when creating a dynamic variable, we cannot have access
directly to it, only through a pointer. To dynamically allocate a variable,
we will have to use the new operator:
int *apont = new int;
To understand what is happening in the example above, see the following diagram:
Scheme:

1 - We declare a pointer to an integer (int *pointer)


[Link]

2 - We created an integer in dynamic memory (using the new operator). Note that the integer that
we create does not have a 'name' (identifier is the more correct term). In order to access it
entirely created in dynamic memory we then have to use a pointer (in this case it is the
pointer
We can later change the value of the created integer like a normal pointer:
*apont = 20;
Do not forget that we are affecting the value pointed by the pointer (a good way to read is
the value indicated by the pointing will be equal to 20

We can also set a value when we create a variable in dynamic memory:


int *apont = new int(20);
With the creation of dynamic memory, we also have a huge responsibility: to free it.

Free the dynamic memory


While static memory is automatically released by the program (we do not need to
We need to worry about it), dynamic memory has to be freed by the programmer. If we ...
forgetting to free her will always persist. It will then use system resources or even
exhaust all the system's memory. Moral of the story: never forget to free up memory.
after they create it (when they no longer need it, of course).
To free the created memory, the delete operator is used.
int *pointer = new int(20);

do something....

delete pointer;
Simple, but its forgetfulness is the cause of many serious program errors.....
Note:

Ao fazermosdelete apont;estaremos a libertar a variável criada emnew int(20);e não o apontador


point. We do not have to worry about it, since it is a statically created pointer and
will be eliminated statically.
Tip:

It is strongly recommended that you set pointer = NULL; after delete pointer;
As I explained in the examples above, doing delete only clears the variable from memory.
dynamic. The pointer will continue to point to the same address as before.
To prevent the programmer from using it by mistake (after we have eliminated it), when doing 'apont = '
NULL; we are making the pointer not point to anything, and we can use a
condition to know if the pointer exists:

if (!apont) //the same as if (apont == NULL)


//...
[Link]

Dynamically allocating and freeing arrays


Dynamically allocating an array is as simple as allocating a normal variable:
int *array = new int[100]; // allocates an array with 100 ints
and to free the memory:
delete [] array;

Operations with the address


To illustrate a simple operation with variable addresses, see the example below:
#include <iostream>
using namespace std;

int x = 20;
int y = 10;
int *pointer; // pointer to a variable of type int

void printthis();

int main()
{

pointer = &x; //the pointer takes the value of the variable's address

printthis();

The address will be incremented by a value, press ENTER.


endl;
[Link]();

pointer++;

printthis();

[Link]();
return 0;
}

void printthis()
{
cout << "Variable x:" << endl;
Value of x:
cout << 'Address of x: ' << &x << endl;

Variable y:
Value of y:
cout << "Address of y: " << &y << endl;

Pointer variable:
Value of pointer:
cout << "Pointer address: " << &pointer << endl;
cout << "Value of the variable pointed to by pointer (x): " << *pointer <<
------------
}
[Link]

Example 14.1 - operations with the address


What gives me the following output

Variable x:

Valor de x: 20
Address of x: 0x434000

Variable y:

Valor de y: 10
Address of y: 0x434004

Pointer variable:

Pointer value: 0x434000


Pointer address: 0x437010
Value of the variable pointed by pointer (x): 20
------------

The address will be incremented by a value, press ENTER.

Variable x:

Valor de x: 20
Address of x: 0x434000

Variable y:

Value of y: 10
Endereco de y: 0x434004

Pointer variable:

Pointer value: 0x434004


Pointer address: 0x437010
Value of the variable pointed to by pointer (x): 10
Como podem ver ao incrementarmospointerestamos na verdade a fazer com que pointer tome o
address of the following variable (4 bytes later), allowing you to interfere with its value.
Note:

This example was only to explain a simple operation with the address. The address itself
The example is not very correct, because in real situations, nothing guarantees that the variable that is
positioned later in memory is the variable we intend to use.

Pointers and arrays


A pointer is equivalent to the address of the first element it points to. Thus:
#include <iostream>
using namespace std;
[Link]

int array[10];
int *pointer;

int main()
{
pointer = array;
array[0] = 50;

array =
cout << "pointer = " << *pointer << endl;

[Link]();
return 0;
}

Example 14.2 - Pointers vs Arrays (Test I)


It would give the same result. We could then take advantage of this to access the other elements of
array. For example, if we want to access element number 7:
#include <iostream>
using namespace std;

int array[10];
int *pointer;

int main()
{
pointer = array;
array[7] = 50;

array =
pointer =

[Link]();
return 0;
}

Example 14.3 - Pointers vs Arrays (Test II)


In fact, an array is a kind of pointer. Like this:
#include <iostream>
using namespace std;

int array[10];
int *pointer;

int main()
{
pointer = array;
array[0] = 50;

array =
pointer =

[Link]();
return 0;
}
[Link]

Example 14.4 - Pointers vs Arrays (Test III)


And also:
#include <iostream>
using namespace std;

int array[10];
int *pointer;

int main()
{
pointer = array;
array[7] = 50;

array =
pointer =

[Link]();
return 0;
}

Example 14.5 - Pointers vs Arrays (Test IV)


In fact, when we use square brackets ( [] ), we are using an operator of
dereference, called offset operator or in Portuguese indexing operator. Thus we can
to do
#include <iostream>
using namespace std;

int main()
{
int array[2];
int *pointer;

pointer = array;

array[0] = 0;
pointer[1] = 1;

for (int i = 0; i < 2; i++)


{
Array[<i>] = <array[i]>
pointer[
}

[Link]();
return 0;
}

Example 14.6 - Pointers vs Arrays (Test V)


That is equivalent to doing:
array[10] = 15;
what to do:
[Link]

(array+10) = 15;
This becomes especially useful for functions. So far we have never used arrays as arguments.
of functions, see how in the following example:
#include <iostream>
using namespace std;

int clear_array(int *array, int size);

int main()
{
const int SIZE = 10; //constant variable

int array[TAMANHO];
list[0] = 4; //just to test if the array has been cleared

cout << lista[0] << endl;

clear_array(list, SIZE);

cout << lista[0] << endl;

[Link]();
return 0;
}

int clear_array(int *array, int size)


{
for (int i = 0; i < size; i++)
{
array[i] = 0;
}
}

Example 14.7 - Clear array function


So what is the difference between a pointer and an array? The main difference is that the size of
an array must be constant, while the size of a pointer (used for memory
Dynamics) can vary. See the following example (an improved version of the example above:
#include <iostream>
using namespace std;

int clear_array(int *array, int size);

int main()
{
int size;

Enter a size for the array (less than 1000, and only one
suggestion) << endl;
cin >> size;

int *list = new int [size];

list[0] = 4; //just to test if the array has been cleared


[Link]

cout << lista[0] << endl;

clear_array(list, size);

cout << list[0] << endl;

[Link]();
[Link]();
return 0;
}

int clear_array(int *array, int size)


{
for (int i = 0; i < size; i++)
{
array[i] = 0;
}
}

Example 14.8 - Clear array function (version 1.1)


As you can see, a very small change brought a great feature to this program
(although it continues to serve for practically nothing :)
End of lesson 14 of C++:
Next classC++ 15 - Classes - Part II
Download thesource codetwo examples from the class
Download the class in PDF (Coming Soon)

Go to the top of the page

Class 15 - Classes - Part II


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

constructor, a method of a class that is executed when the object is created


-destructor, a method of a class that is executed when the object is destroyed
-operator is used to assign operators to classes
this, um pointer that points to the object it contains
[Link]

Builders
Frequently, an object needs to initialize some variables or allocate dynamic memory.
when it is initialized. For this purpose, a class can have a function for the purpose, the constructor,
which will be called automatically when the class is initialized. For example, let's imagine a
class Rectangle:
class Rectangle
{
public

Basic functions for changing values and return


void changeX(int a) { x = a; }
void changeY(int a) { y = a; }
void changeHeight(int a) { height = a; }
void changeWidth(int a) { width = a; }

void changeValues(int x_, int y_, int height, int width);

int getX() { return x; }


int getY() { return y; }
int getHeight() { return height; }
int getWidth() { return width; }

//calculation functions
int area() { return width * height; }
int perimeter() { return (width * 2) + (height * 2); }

private

int x, y; //coordinates of the top left corner of the rectangle


int altura, largura; //altura e largura do rectangulo
};

void Rectangle::changeValues(int x_, int y_, int height, int width)


{
changeX(x_);
changeY(y_);
changeHeight(alt);
changeWidth(width);
}

Example 15.1 - Rectangle Class


The class is perfectly functional, but does it not require a constructor? Note that for
to perform some operation (such as knowing the area, etc.) we need to have the variables defined. A
the constructor ensures that the programmer will not make this basic mistake. Creating a constructor is
quite easy:
Class_Name();
If the class is named Rectangle, the constructor should be:
Rectangle();
Except for the fact that a constructor does not return any type of data, it is treated as a
normal function. In the example above, from the Rectangle class, a constructor could be:
[Link]

class Rectangle
{
public

Rectangle(int x_, int y_, int height, int width);

basic functions for changing values and return


void mudarX(int a) { x = a; }
void changeY(int a) { y = a; }
void changeHeight(int a) { height = a; }
void changeWidth(int a) { width = a; }

void mudarValores(int x_, int y_, int alt, int larg);

int getX() { return x; }


int getY() { return y; }
int getHeight() { return height; }
int getWidth() { return width; }

//calculation functions
int area() { return width * height; }
int perimeter() { return (width * 2) + (height * 2); }

private

int x, y; //coordinates of the top left corner of the rectangle


int altura, largura; //altura e largura do rectangulo
};

Rectangle::Rectangle(int x_, int y_, int height, int width)


{
changeValues(x_, y_, height, width);
}

void Rectangle::changeValues(int x_, int y_, int height, int width)


{
changeX(x_);
changeY(y_);
changeHeight(alt);
changeWidth(width);
}

Example 15.2 - Rectangle Class (version with constructors)

Destructors
Destructors do precisely the opposite of constructors. When the class is destroyed
(depending on your lifespan) will execute the destructor. Destructors are great for deallocating
dynamic memory (and thus avoid many forgettings).
Just like constructors, destructors do not return any value and are defined by the name of the
, preceded by a tilde (~):
~Class_Name();
I'll just leave an easy example:
#include <iostream>
using namespace std;
[Link]

class Test
{
public
Test();
~Test();
};

Test::Test()
{
Started the object
}

Test::~Test()
{
The object has been destroyed
}

int main()
{
Test *t = new Test; //we can also dynamically initialize objects

[Link]();
Press ENTER to destroy the object.

delete t;

[Link]();
return 0;
}

Example 15.3 - Tests with Destructors


I used dynamic memory because we can destroy it whenever we want, although if I used one
block, it would have the same effect.

Pointers for classes


We can use pointers for classes (or structures) in the same way we use them for a
variable.
Class *test;

//...

(test).x = 3;
(test).y = 1;
However, to simplify the code further, a new method was created, specifically for
classes or structures:
Class *test;

//...

test->x = 3;
teste->y = 1;
[Link]

Defining operators
Let's look at the following piece of code:
int x, y, z;

//...

z = x + y;
There is nothing strange about this code: it is quite simple and common. Now see the following:
Class x, y, z;

//...

z = x + y;
The above code would compile with an error, but it is completely legitimate for us to want to use a sum if
to resort to more complex methods. We will then have to use the operator statement in the class:
#include <iostream>
using namespace std;

class Point
{
public

int x, y; //the variables are public to save work

Point operator + (Point class) //notice: operator +


{
Temp point; //we will return a temporary class...
temp.x = x + class.x;
temp.y = y + classe.y;
return temp;
}
};

int main()
{
Point a, b, c;

a.x = 10;
a.y = 5;

b.x = 10;
b.y = 15;

c = a + b; //if everything goes well, c.x is 20 and c.y is also 20

cout << "C.x = " << c.x << " and C.y = " << c.y << endl;

[Link]();
return 0;
}

Example 15.4 - Point Class (operator +)


[Link]

In this example, we use the operator function along with the + operator, which deals with addition.
+).
There are several operators that can be used in conjunction with the operator instruction. Among them we have: +,
-, *, /, [], new, delete, %, etc, and we will use them in the same way, for example:
Point operator - () or Point operator new () or Point operator [] ()

Pointer this
The sharpener this is a very special sharpener, which represents the object itself. See the example
next:
#include <iostream>
using namespace std;

class Point
{
public

int x, y; //the variables are public to save work

Point& operator = (const Point class) //function to equal objects


{
x = class.x;
y = class.y;
return *this; // by doing return *this we are returning
the object itself, so we do not need to create
//a temporary object
}
};

int main()
{
Point a, b;

a.x = 10;
a.y = 5;

b = a;

A: X =
B: X =

[Link]();
return 0;
}

Example 15.5 - Point Class (operator =)


The only confusion they might feel is in the expression Point&operator....
They just need to know that when they need to return the pointer, they will have to place the & at
front of the function type (that is, the name of the class).
There is still another use (very useful) for the this pointer. In the examples above, we often have,
used some variable names (x_ for example) to avoid conflicts with the names of
variables that are within the class. We can solve this problem through the this pointer:
[Link]

class Rectangle
{
public

Rectangle(int x, int y, int height, int width);

//basic functions to change values and return


void changeX(int x) { this->x = x; } //note! the object's x will be equal
//to x of the function
void changeY(int y) { this->y = y; }
void changeHeight(int height) { this->height = height; }
void changeWidth(int width) { this->width = width; }

void changeValues(int x, int y, int height, int width);

int getX() { return x; }


int getY() { return y; }
int getHeight() { return height; }
int getWidth() { return width; }

//calculation functions
int area() { return width * height; }
int perimeter() { return (width * 2) + (height * 2); }

private

int x, y; //coordinates of the upper left corner of the rectangle


int altura, largura; //altura e largura do rectangulo
};

Rectangle::Rectangle(int x, int y, int height, int width)


{
changeValues(x, y, height, width);
}

void Rectangle::changeValues(int x, int y, int height, int width)


{
mudarX(x);
changeY(y);
changeHeight(alt);
changeWidth(width);
}

Example 15.6 - Rectangle Class (using the this pointer)


Don't forget that the attributes of a function (what's between parentheses ()) are local and only
exist in this function. We can then make this->x = x; which means the variable x of the object will be
equal to the variable x (which was assigned to the function).

Headers
Classes are usually placed in a special type of file, the headers (*.h), for a
easier reuse of the same. I will take the example of the Rectangle class and put it in two
separate files: rectangle.h (the header that contains the class declaration) and the
[Link] (which contains the code with the method definitions of the class):
rectangle.h
[Link]

#ifndef _RECTANGLE_H_
#define _RECTANGULO_H_

class Rectangle
{
public

Rectangle(int x, int y, int height, int width);

//basic functions for changing values and return


void changeX(int x) { this->x = x; } //note! the object's x will be equal
the x of the function
void changeY(int y) { this->y = y; }
void changeHeight(int height) { this->height = height; }
void changeWidth(int width) { this->width = width; }

void changeValues(int x, int y, int height, int width);

int getX() { return x; }


int getY() { return y; }
int getHeight() { return height; }
int getWidth() { return width; }

//calculation functions
int area() { return width * height; }
int perimeter() { return (width * 2) + (height * 2); }

private

int x, y; //coordinates of the top left corner of the rectangle


int height, width; // height and width of the rectangle
};

#endif

Example 15.7 - rectangle.h


[Link]
#include "rectangle.h"

Rectangle::Rectangle(int x, int y, int height, int width)


{
changeValues(x, y, height, width);
}

void Rectangle::changeValues(int x, int y, int height, int width)


{
changeX(x);
changeY(y);
changeHeight(alt);
changeWidth(width);
}

Example 15.7 - [Link]


There are only 3 lines that deserve explanation:
[Link]

#ifndef _RECTANGLE_H_
#define _RECTANGLE_H_
#endif
When we do #include "rectangulo.h" we are calling the content of rectangulo.h. Now, in the
the example I gave, we are obliged to call it at least 2 times. To avoid code conflicts.
we are required to include these instructions (from the preprocessor, which will be given in future classes).
Follow the following reasoning:
If Not Defined
Define_ANY_NAME_
class
End If (stop the condition)
When naming the class, we must take into account that we will never use the same name in a
variable (or in the preprocessor), which is why it is usually named: CLASS_NAME_H
YOU_NAME_OF_THE_CLASS_H_
To finish, an example of how to use the two files (rectangulo.h and [Link]) in a
program:
[Link]:
#include <iostream>
#include "rectangle.h"
using namespace std;

int main()
{
Rectangle rect(10, 5, 20, 10);

cout << "Area before: " << [Link]() << endl;

[Link](5);

cout << "Area after: " << [Link]() << endl;

[Link]();
return 0;
}

Example 15.7 - [Link]


End of lesson 15 of C++:
Next classC++ 16 - Relationships between Classes
Download thesource codetwo examples from the class
Download the class in PDF (Coming Soon)

Go to the top of the page

Lesson 16 - Relationships between classes


<!--
[Link]

google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

generalization, relationship between classes, where there is a parent class (general) and other more specific ones,
What do the members of the parent class (subclasses) inherit? 'is a' relationship.
-protected, a keyword that acts on the accessibility of the members of a class. They cannot be
accessed outside this class (similar to private members), except in the case of
association, in which the child classes can access the protected members of the parent class
Aggregation, relationship between classes, where one class has as a member an object of another class.
It implies a 'has a' relationship.
A class that is a "friend" of another can access its private members.
Polymorphism is the ability of objects of different types (classes) to respond to
methods with the same name, each having a specific behavior for each type
(class) (definition of theEnglish Wikipedia)

Relations between classes


In large projects (like a game), one starts by planning the code. This planning is done at
level of class selection and the selection of relationships between them.
The OOP (Object-Oriented Programming) paradigm provides for two major types of relationships between
classes:
Generalization
Aggregation
This class will try to explain the use and importance of these relationships.

Generalization (through Inheritance)


Let's imagine that we are developing an RPG and that there are different races that, although with the
their individual characteristics share several features among themselves. In this case, we could
create a general class called 'Being', and several more specific classes. When we create a
generalization will imply an 'is a' relationship (for example, Human is a Being)
Imagine that this is the class Being:
class Ser
{
public:
void move(); //all beings (animals) move
void sleep(); //everyone sleeps

... It seems that it doesn't speak


If a certain breed does not speak, this message will appear... you will see already
[Link]

follow its use

private
int hp; //Health Points or Health Points
};

Okay, I know it's a bit of a weak representation, but I'm out of ideas :)
What is important in this class is that it will be the general one, through which all the others that follow will be.
exposures will be generalized.
Now some possible examples of generalized classes of the class Being:
class Human : public Being // Human class, derived from Being class
{
public
//move and sleep are already in general

void speak() { cout << "Did you call?" << endl; }


As you can see, although there is already a method 'speak' in the general class,
this does not affect this method
void attack();

private
int strength; // the character's strength.
};

class Magico : public Ser


{
public

void speak() {
cout << "How can the powers of my spells help you?" << endl;
}

void castSpell();

private
int mp; // Magic Points or Magic Points
int magic; //the character's magic power
};

class Orc : public Ser


{
public

void attack();

private
int strength; // strength with which the Orc attacks.
};

Do you see how easy it is to generalize? All you have to do is add two words.
code:
class GeneralizedClass : public GeneralClass
Now see an example of the use of the classes above (compilable program):
[Link]

#include <iostream>
using namespace std;

class Ser
{
public
void mover(); // all beings (animals) move
void sleep(); //everyone sleeps

void speak() { cout << "... It seems that it doesn't speak" << endl; }
If a certain breed does not speak, this message will appear... you will already see the
follow its use

private
int hp; //Health Points or Health Points
};

class Human : public Being // Human class, derived from the Being class
{
public
move and sleep are already in the general

void speak() { cout << "Did you call?" << endl; }


As you can see, although there is already a 'speak' method in the general class,
this does not affect this method
void attack();

private:
int strength; // the character's strength.
};

class Magico : public Ser


{
public

void speak() {
How can the forces of my spells help you?
}

void castSpell();

private
int mp; // Magic Points or Magic Points
int magic; //the character's magic strength
};

class Orc : public Ser


{
public

void attack();

private
int strength; // strength with which the Orc attacks.
};

int main()
{
Human we;
[Link]

Magic magician;
Orc orc;

[Link]();
[Link]();
[Link]();

[Link]();
}

Example 16.1 - Class Being and other subclasses


Note:

Each class has its own constructor and destructor, that is, a generalized class cannot
inherit the constructor of the superclass.

The protected type


Before proceeding further, I will talk to you about the protected access type.
At this point in the classes, you should already know well what the private (private) and public (public) types are.
Classes. Very well, now, with the introduction of inheritance, they should learn the protected type.
Basically:
Private members cannot be accessed by any object, except through the object itself.
class.
Protected members can be accessed only by the class itself and by derived classes.
through inheritance.
Public members can be accessed both inside and outside the class.
Thus, in the example above, the derived classes of the function 'to be' could not access the variable hp.
We can easily solve this issue:
class Ser
{
public
void mover(); //all beings (animals) move
void sleep(); //everyone sleeps

... It seems that it doesn't speak


If a certain race does not speak, this message will appear... you will see already the
continue its use

protected
int hp; //Health Points or Health Points
};

Aggregation
Aggregation implies a "has a" relationship. For example, a Human has clothing and two
weapons (knife and sword).
[Link]

class Human : public Being // Human class, derived from the Being class
{
public
moving and sleeping are already in the general ones

void speak() { cout << "Did you call?" << endl; }


As you can see, although there is already a method "speak" in the general class,
this does not affect this method
void attack();

private
int strength; // the character's strength.
Clothes clothes;
Sword weapon;
Carry a knife;
};

Generalization vs Aggregation
In some cases, it may seem difficult to distinguish between the two relationships, which leads to the use of
inappropriate from the inheritance. The inheritance should only be used in obvious cases to avoid confusion.
futures. For example, a Car class should be a generalization of the Engine class, only
because the Motor class is the most important class (which contains power, km/h...). A car
certainly it is not a engine, just a motor.
This explanation may seem a bit confusing, but in the future you will see that the poor distinction between
these two types of relationships can lead to a complete rewrite of the code (I know from experience
own)

Friend Classes
In C++, it is possible for a class to access the private and protected members of a
function. Just declare it as friend.
#include <iostream>
using namespace std;

class UM
{
private: //to tell the truth, we didn't even need this private:
int x;
friend class DOIS; //the class DOIS is a friend of class UM, that's why the class
DOIS can access the private members of the UM class.
};

class DOIS
{
public
void setX(int x) { classe.x = x; }
void printX() { cout << classe.x << endl; }

private
A class;
};

int main()
[Link]

{
TWO
[Link](30);
[Link]();
[Link]();
return 0;
}

Example 16.2 - Test of a 'friend' class

Polymorphism
Polymorphism can be defined as "the ability of objects of different types (classes) to be able to
responding to methods with the same name, each having a specific behavior for
each type (class) (translated from the definition of the)English Wikipedia)
But what does this mean in practice? We have already seen that a derived class shares with the parent class, the
public and protected members of it. But that's not all: the type of pointer of a class
the derivative is compatible with that of the mother class, that is, in the examples above (class Being), we could
do something like:
Magical jog1;
Player *jogador = &jog1;
As you can see, we are taking the pointer for the general class (Being) and making it point
for a generalized class (Magical). That is, the player will be a magician. In the same way,
it could be done:
Player *jogador = new Magician;
The player object will thus belong to the Magico class. This is quite useful when we want to change
the type of classes in runtime, that is, by user action, while the game runs.
You can also use this in functions, for example:
#include <iostream>
using namespace std;

class Ser
{
public
void move(); // all beings (animals) move
void sleep(); //everyone sleeps

... It seems that it does not speak


If a certain breed does not speak, this message will appear... you will see already the
continue its use

private
int hp; //Health Points or Health Points
};

class Human : public Being // Human class, derived from the Being class
{
public
moving and sleeping are already included in the general

Did you call?


[Link]

As you can see, even though there is already a method called 'speak' in the general class,
this does not affect this method
void attack();

private
int strength; // the character's strength.
};

class Magico : public Ser


{
public

void speak() {
How can the forces of my spells help you?
}

void castSpell();

private
int mp; // Magic Points or Points of Magic
int magic; //the character's magic power
};

class Orc : public Ser


{
public

void attack();

private
int strength; // strength with which the Orc attacks.
};

void speak(Person *person); //speak function. Note that it takes as an attribute a


//pointer to an object of the class Ser

int main()
{
Human, human;
Magical mag;
Orc orc;

speak(&hum); // it is obvious that we have to pass the address of the object


//because we want the object itself to be processed...
speak(&mag);

speak(&orc);

[Link]();
}

void speak(Being *person)


{
person->speak();
}

Example 16.3 - Speak function (without virtual functions)


[Link]

Thus, the first requirement of polymorphism is fulfilled. A single object can assume
several classes. However, when we do player->speak() (don't forget that it's a pointer, and
that's why you need '->' instead of '.', it doesn't call the method of the specific class, but rather the
general class method (Being). This causes, in the above example, to show the expression three times...
It seems that he/she does not speak.

It is then necessary to fulfill the second requirement of polymorphism, which can be easily resolved.
using a single keyword: virtual:
#include <iostream>
using namespace std;

class Ser
{
public
void move(); //all beings (animals) move
void sleep(); // everyone sleeps

virtual void speak() { cout << "... It seems that he doesn't speak" << endl; }
If a certain race does not speak, this message will appear... they will already see the
continue its use

private
int hp; //Health Points or Health Points
};

class Human : public Being // Human class, derived from the Being class
{
public
moving and sleeping are already in the general

Did you call?


/* Como podem vêr, embora já exista um método "falar" na classe geral,
this does not affect this method */
void attack();

private
int strength; // the character's strength.
};

class Magico : public Ser


{
public

void speak() {
cout << "How can the forces of my spells help you?" << endl;
}

void castSpell();

private
int mp; // Magic Points or Magic Points
int magic; //the character's magic strength
};

class Orc : public Ser


{
public
[Link]

void attack();

private
int strength; // strength with which the Orc attacks.
};

void speak(Person *person); //speak function. Note that it takes as an attribute a


pointer to an object of class Ser

int main()
{
Humanoid hum;
Magical mag;
Orc orc;

speak(&hum); // it is obvious that we have to pass the object's address


//pois queremos que seja processado o objecto em si...
speak(&mag);

speak(&orc);

[Link]();
}

void speak (Person *person)


{
person->talk();
}

Example 16.4 - Speak function (with virtual functions)


The keyword virtual is what makes the polymorphism mechanism work. When we define the
to talk about the parent class method (Being) as virtual, this method will not be called by subclasses.
(calling the specific method of each one).
Polymorphism is very important in object-oriented programming, as it provides us with a
way to dynamically change the complete total of an object.
End of class 16 of C++:
Next classC++ 17 - Advanced C++ Techniques - Part I
Download thesource codetwo examples from the lesson
Download the lesson in PDF (Coming Soon)

Go to the top of the page

Class 17 - Advanced C++ Techniques - Part I


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
[Link]

google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

overload of functions, functions with the same identifier, but with different arguments/return type
different.
-predefined parameters, arguments that take on a certain value, when the user
does not specify it
constants, variables that assume only one value (cannot be changed), at the time of declaration
the same.
static members, members of a class with the same lifespan as a global variable,
but with the scope of a local variable. They are common to all objects of a class.
static methods, methods of a class that can be called without creating an object.
-pointers to functions, pointers that point to a function. They have the particularity of
it can be changed at will (it can point to any function) at runtime.

Advanced C++ Techniques


In fact, the objective of the next lessons is to teach some very useful techniques that can
go through algorithms, class creation, new instructions and new libraries (STL, for example).
They do not mean, therefore, that they are complicated; they are merely intended to help solve some
problems, or find better solutions for your games.

Function overloading
In C++ we can have multiple functions with the same identifier, but with different
arguments/code. For example, imagine a function that calculates the area of a rectangle:
#include <iostream>
using namespace std;

void area (int c, int l);


void area (double c, double l); //it is a function with the same identifier, but in
//realities are actually quite different

int main()
{
area (2, 4); //the function int area will be called

area (5.2, 1.3); //the function double area will be called

[Link]();
return 0;
}

void area (int c, int l)


{
This is using the function int area
Area = (c * l)
}

void area(double c, double l)


[Link]

{
This is using the double area function
Area =
}

Example 17.1 - Area Function - Function Overloading


As you can see, the difference between the two, which causes the overload of the functions, is the
type of arguments. Also, the number of arguments of a function can provoke its
overload, for example:
int sum(int x, int y);
int sum (int x, int y, int z);
This becomes quite useful in the interface between a class and the programmer, for example:
int area (Rectangle rect);
int area (int length, int width);
Tip:

Normally, the code between functions that are 'overloaded' does not differ much, as
it only differs in the treatment of the data (changes the type of variables or adds another variable,
for example), in order to avoid confusion in the code.

Predefined parameters
A function can have optional parameters, where the programmer may or may not, depending on
your needs, assign values. If you do not assign a value to the parameter, a default will be given to it
default value, which was chosen earlier, in the function definition. Imagine the following
sum function:
#include <iostream>
using namespace std;

int sum(int a, int b, int c = 0); // c is equal to 0, so as not to


interfere
in the sum operation

int main()
{
int x = sum(4, 3);
int y = sum(3, 7, 6);

X:

[Link]();
return 0;
}

int sum (int a, int b, int c) // note that in the definition of the function it is not
I need
// set c = 0, only in the declaration (above)
return (a + b + c);
}
[Link]

Example 17.2 - Sum Function - Default Parameters


As it turns out, it is very useful and we can provide a choice regarding the variables to use. This can result in
well when creating a game engine, as we can give them the choice to use arguments or not in
function (if you choose not to use it, its value will be up to the function's programmers).
Note also that you can only set the predefined values either in the declaration or in the definition of the
function, never both of us. Usually placed in the declaration, because it is the one that appears in the
header files.
It remains to say that, for obvious reasons, only predefined values can be used in the last parameters.
of the function. For example:

f(int x = 0, y, z = 0);
It is not correct.

Arrays as function arguments


As we had already seen, passing an array to a function is quite easy:
#include <iostream>
using namespace std;

int sum (int array[], int size);

int main()
{
int array[5] = {2, 4, 5, 2, 1}; //creates an array of 5 integers

cout << "Sum: " << sum(array, 5) << endl;

[Link]();
return 0;
}

int sum (int array[], int size)


{
int value = 0;
for (int i = 0; i < size; i++) //loops through the array, from 0 to 4
{
value += array[i]; // keeps adding....
}

return value;
}

Example 17.3 - Sum of the Elements of an array


When an array is passed as an argument to a function, it will not create a copy of it.
in memory (as it normally does with any variable), but rather create a pointer to its
first element. Thus, when we modify an array inside a function we are really
change this array outside the function (remember references and pointers).
In summary, if we pass an array to a function and modify the array inside the function, then afterward
[Link]

from this processing the array will remain changed (unlike variables, which can only be
altered through references and pointers).
#include <iostream>
using namespace std;

void duplicate(int array[], int size);

int main()
{
int array[5] = {2, 4, 5, 2, 1}; // creates an array of 5 integers

Array normal:

for (int i = 0; i < 5; i++)


{
[i] - array[i]
}

Array after duplication:

duplicate(array, 5);

for (int i = 0; i < 5; i++)


{
[i] - array[i]
}

[Link]();
return 0;
}

void duplicate (int array[], int size)


{
for (int i = 0; i < size; i++) //iterates through the array, from 0 to 4
{
array[i] *= 2; //multiplies each number by 2
}
}

Example 17.4 - Duplicate the elements of an Array


As you can see, we do not need to use pointers/references to change the value through the
function. By the way, as I had explained, an array and a pointer are very similar. Therefore, the
the example below is practically the same as the one above:
void duplicate(int *array, int size)
{
for (int i = 0; i < size; i++) // loops through the array, from 0 to 4
{
*array *= 2; //multiplies each number by 2
array++; //move the address of the pointer/array, to capture the value
next
}
}
[Link]

Constants
C++ accepts constant variables, meaning variables that have a fixed value. If we try to change the
the value of the variable the compiler will consider as an error and will not allow compilation. There are several
advantages of considering variables as constants, especially with pointers and in methods
of classes.
A constant variable is defined as follows:
const variable_type variable_name = constant_value;
For example:
const int x = 9;
const float pi = 3.14;
Don't forget that you always have to assign a value when defining the variable. The example
next will be error:
const float pi;
pi = 3.14;
One advantage of creating a constant pointer to a variable is to ensure that the variable
pointed should not be modified (we will be creating a read-only variable, for reading only):
#include <iostream>
using namespace std;

int main()
{
int x = 30;
const int *pointer = &x;

*pointer = 2; <- Daria error

cout << *pointer << endl;

[Link]();
return 0;
}

Example 17.5 - Constant Pointer


We can also create constant methods within classes. These have the advantage of not
they can modify no variable in the object, which prevents some programming errors.
class Monster {
public
void setID(int id) { this->id = id; }
const int getID()
{
// id = 2; <- this would cause an error, since we cannot change the object
return id;
}
private
int id;
}
[Link]

In summary, creating constant variables/methods serves primarily to prevent that the


programmers make mistakes due to distraction. It is, therefore, useful if the code is distributed across several
programmers, so that they know which variables they cannot change.

Static members
A static variable is a single variable for all objects of a class. This variable has
the same lifetime as a global variable, but has the same scope as a member
of an object.
See below a common use of static members, for counting the number of objects of a
class:
#include <iostream>
using namespace std;

class Monster {
public

static int number; // the number of monsters in the entire program

Monster(char *name) // constructor


{
this->name = name;

number++; //the static variable will be incremented


}

private
char *name;
};

int Monstro::number = 0; //we need to initialize the variable globally

int main()
{
Orc monster("Orc");
Monster spider("Spider");
Monster goblin("Goblin");

cout << "Number of Monsters: " << Monstro::number << endl;


[Link]();
return 0;
}

Example 17.6 - Monster Class - Static Members


As you can see, they are very useful since they exist independently of the object, but
they continue to be part of the class. Just look at the following line of code:
int Monstro::number = 0;
In order to access a static member, we will always have to initialize it as a variable.
global.
[Link]

Static methods
We can also create static methods. These have the particularity of being callable
without having created an object of the class. For example, imagine the following Math class:
#include <iostream>
using namespace std;

class Math {
public

static int add(int a, int b) { return a + b; }


static int subtract(int a, int b) { return a - b; }
static int multiply(int a, int b) { return a * b; }
static int divide(int a, int b) { return a/b; }
};

int main()
{
int x = Math::add(4, 5);
int y = Math::divide(20, 4);

int z;
Math m;

z = [Link](6, 2); // this was just to show that we can access


normally
through the object to static methods. The same
// happens for static members

cout << "X: " << x << ", Y: " << y << endl;
[Link]();
return 0;
}

Example 17.7 - Math Class - Static Methods

Function Pointers
Function Pointers (I think the correct term in Portuguese is function pointers :) are very
useful in programming. Here I will only show an easy example. For instance, imagine that
we wanted to create a complete calculator that offered the programmer a simple function that,
without resorting to conditional operators (if, else, switch) allowed to carry out the 4 basic operations of
mathematics (adding, subtracting, dividing, and multiplying). Function pointers would allow this.
A function, just like a variable, has an address in memory. We can then place a
pointer to the same among the arguments of a function and call it. For example, we could
to do
int
See the example below, of the so-called calculator:
#include <iostream>
using namespace std;

int add(int a, int b) { return a + b; }


int subtract(int a, int b) { return a - b; }
[Link]

int multiply(int a, int b) { return a*b; }


int divide(int a, int b) { return a/b; }

int main()
{
int (*calculator)(int a, int b); // we created a pointer to a function

calculator = add; // calculator now points to the add function

int x = (*calculator)(4, 6);

calculadora = multiplicar; //calculadora passa a apontar para a função somar

int y = (*calculator)(4, 2);

X: x, Y: y

[Link]();
return 0;
}

Example 17.8 - Calculator Functions - Function Pointers


I admit it may seem a bit confusing, but it's nothing out of the ordinary. Let's see:
int (*calculator)(int a, int b); - we are creating a pointer for functions. This pointer in
specific can point only to functions that have two arguments of type point
the name does not need to be a or b, as we will see later) and that return variables of the tipoint.
calculator = add; this doesn't even need explanations. We are making the cursor
calculator point to the function add.
int x = (*calculator)(4, 6); - in order to access the function pointed to by the pointer
calculator we have to use the dereference operator (*). And, of course, introduce the arguments.
Tip:

In the declarations of a function, we are not required to specify the names of the arguments (only the
type of variable), but we are required to specify the name in the definition. Thus, we could have
done:int (*calculator)(int, int);

This does not apply only to pointers to functions, but to all types of functions, as long as it is in their
definition: int f(int, int); for example
It wasn't that difficult, was it? Now let's see a slightly more complicated example,
using an intermediate function.
#include <iostream>
using namespace std;

int add(int a, int b) { return a + b; }


int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) { return a/b; }

int calculator(int a, int b, int (*operation)(int, int));


[Link]

int main()
{
int x = calculator(4, 6, add);
int y = calculator(4, 2, multiply);

X: x, Y: y
[Link]();
return 0;
}

int calculator(int a, int b, int (*operation)(int, int))


{
int result = operation(a, b);

return result;
}

Example 17.9 - Calculator Function - Pointers to Functions


int calculator(int a, int b, int (*operation)(int, int));
This function declaration is completely normal... until we get to the last parameter. If you notice,
without the '*' this parameter would be exactly a function: int operation (int, int).
With this instruction, we are telling the program to accept functions that have two
integer arguments that return an integer value.
int x = calculator(4, 6, add);
As you can see, we are passing the function as if it were a variable (it is a pointer, in
truth).
End of class 17 of C++:
Next classC++ 18 - Advanced C++ Techniques - Part 2
Download thesource codetwo examples from the class
Download the class in PDF (Coming Soon)

Go to the top of the page

Lesson 18 - Advanced C++ Techniques - Part II


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
[Link]

Key Concepts:

STL, Standard Template Library, a library that is part of the C++ standards and that
adds many features, such as the string library
template, a C++ mechanism that creates a generic variable that can take any type
variable (including classes created by the programmer)
-namespace, allow grouping variables, functions, or classes within them, in order to avoid
confusions with variables/functions/classes with the same name
string library, a library that is part of the STL and encompasses resources for processing
strings

STL - Introduction
In this class, I will address STL (Standard Template Library). STL is a library created to help the
programmer, with various data structures and algorithms. It is important to learn to work with
this library, since the code it contains is very useful (I bet they will use it at least
once) and is part of the C++ standards. You have already used this library, as the string class
It is one of the several present in it (and as you must have seen, it is very useful).

Templates in functions
The library is called STL, as it uses the C++ template mechanism. This mechanism
it allows to create a kind of 'generic variable' that can operate with any type of variables.
Nalast classwe learned that we could use different functions with the same name, but
with different types of variables. With templates, we can create a generic function that can
operate with all types of variables/classes. For example, it would be great if we could create
just a function as an alternative to the following 3:
int sum(int a, int b);
double sum(double a, double b);
char add (char a, char b);
Thus, through the use of templates, the generic function would look like this:
template <class Type> Type add (Type a, Type b);
You must have noticed that the syntax is quite different from what we are used to seeing, but I will
try to explain everything properly: First we have to take into account the syntax of the templates:
template <class identifier> function_declaration;
or
template <typename identifier> function_declaration;
No exemplo acima utilizei a primeira declaração, mas não há nenhuma diferença entre as duas
(by the way, the next example will follow the second one, to show that it is the same). We can give a name
any to the identifier (in the example above I chose the name "Type", which should work for the largest)
part of the cases). Here is an example of a program that uses templates
#include <iostream>
using namespace std;

template <typename Type>


Type add (Type a, Type b)
{
return a + b;
}
[Link]

int main()
{
cout << "Int - 2+3 - " << add (2, 3) << endl;
Double - 1.53+3.14 -
cout << "Char - '1'+'2' - " << somar ('1', '2') << endl;

[Link]();
return 0;
}

Example 18.1 - Example of Templates in Functions


Note:

The sum of two characters (char type) may seem strange to you. If you have been paying attention to the first
classes, they know that a variable of type char is represented by a number (in binary). This
the number is subsequently converted into a character (following a table). For example, when following
aASCII tableWe know that the value of '1' is 49 and the value of '2' is 50. The sum of the two is
equal to 99, which gives the value of 'c'.

We can also create a template that can work with two different types. For example,
the division function:
#include <iostream>
using namespace std;

template <class T, class U>


T somar (T a, U b)
{
return a + b;
}

int main()
{
cout << "Double and Int - 3.43 + 2 - " << somar(3.43, 2) << endl;
Note that we must put the double first, as it is a number.
decimal
//a função deverá retornar o tipo double.

[Link]();
return 0;
}

Example 18.2 - Templates in Functions - Two Different Types of Variables


Typically, the compiler can determine which variable types to use, but in the case of
we can't manage that, we can easily sort it out, for example:
int x = sum <double, int> (a, b);

Templates in classes
Templates can also be used in classes. As you may have noticed how it works,
[Link]

I will leave only a complete example:


#include <iostream>
using namespace std;

template <class T>


class C_Output //creates a class called C_Output
{
public

T getVar(); //returns the type placed in the template


void setVar(T var);
void print ();

private
T variable;
};

int main()
{
C_Output<double> x; // creates an object of the C_Output class
// the type of the template will be double
C_Output<string> str; //the template will be of type string

[Link](3.14);
[Link]();

[Link]("Hello");
[Link]();

[Link]();
return 0;
}

template <class T>


T C_Output<T>::getVar()
{
return variable;
}

template <class T>


void C_Output<T>::setVar(T var)
{
variable = var;
}

template <class T>


void C_Output<T>::print()
{
cout << variable << endl;
}

Example 18.3 - Templates in Classes


I think the first lines are understandable; I will just leave an explanation for the method definitions.
from class C_Output:
template <class T>
[Link]

T C_Output<T>::getVar()
{
return variable;
}

If the function did not use the template and was of type int, then it would look something like:
int C_Output::getVar()
{
return variable;
}

As you can see, the changes are not that many. We first added the instruction that we would
use a template (template <class T>) so that the function can work with any type of
variables.
Then we put the type of variable that the function returns; as it can return any type of
variable, we chose the type T, from the template.
Then we place the class identifier (C_Output) and specify the type of variable that it
the template will take on; as we do not yet know what type it is, we can use T.
I think you should understand the rest :P

Note:

You can use any type of variables in templates, including classes created by you.

Namespaces
Since theclass number 1We use namespaces, but only now will I explain what they are for.
Basically, namespaces are used to group variables/functions/classes within a name.
way to avoid confusion when working with, for example, other libraries.
This becomes very useful when, for example, they want to create a game engine and
they want to give simple names to the classes/functions/etc. they create, without these conflicting with
other functions that happen to have the same name.
The simplest example:
#include <iostream>
using namespace std;

month_namespace
{
int number = 30; //it can be 31 or 28 or 29, but this is just an example
}

namespace week_days
{
int number = 7;
}

int main()
{
cout << month_days::number << endl;
cout << days_of_week::number << endl;

[Link]();
return 0;
[Link]

Example 18.4 - Example of Namespaces


And a more practical example:
#include <iostream>
using namespace std;

namespace Graphic_Engine
{
void init()
{
Graphics engine started!
}
}

namespace Engine_Som
{
void init()
{
Engine started!
}
}

int main()
{
Engine_Grafica::init();
Engine_Som::init();

[Link]();
return 0;
}

Example 18.5 - Example of Namespaces 2

Using namespace
By using namespace ..., we are 'asking' the compiler to automatically insert
a namespace when necessary. Since the first class we have "asked" the compiler to
automatically include the namespace std. This namespace refers to the standard library.
from C++, which includes cout, endl, cin, etc.
If we did not include using namespace std; at the beginning of the program, we would have to do the following:
#include <iostream>
We are not using the namespace std;

namespace Engine_Grafica
{
void init()
{
Graphics Engine started!
}
}
[Link]

namespace Engine_Som
{
void init()
{
Engine starting up!
}
}

int main()
{
Engine_Grafica::init();
Engine_Som::init();

std::[Link]();
return 0;
}

Example 18.6 - Example of Using Namespace


Another example:
#include <iostream>
using namespace std; //use the namespace std

namespace Graphic_Engine
{
void init()
{
Graphics Engine started!
}
}

namespace Engine_Som
{
void init()
{
Engine of Sound started!
}
}

int main()
{
using namespace Engine_Grafica; // use the namespace Engine_Grafica

init(); //we don't need to put the namespace here


Engine_Som::init(); //but we need, if we want to access Engine_Som

[Link]();
return 0;
}

Example 18.7 - Example of Using Namespace 2


To finish the topic of namespaces: When we use using globally (where we declare
[Link]

as global variables), then this is valid for the whole program. If we use the using in a block,
this is only valid for this same block. For example:
#include <iostream>
using namespace std; //include the namespace globally

namespace Graphics_Engine
{
void init()
{
Graphics Engine started!
}
}

namespace Engine_Som
{
void init()
{
Engine started!
}
}

int main()
{
{
using namespace Engine_Grafica; //use the Engine_Grafica namespace here
block
init(); //we don't need to put the namespace here
}

{
using namespace Engine_Som; //use the Engine_Som namespace in this block
init(); //not here :P
}

[Link]();
return 0;
}

Example 18.8 - Example of Using Namespace 3

STL
After this long introduction, let's finally get to know a bit about the STL.
In fact, you have already used a component of the STL: the string class. As the STL topic is
even though it is very extensive (there are entire books about it), and although I intend to try to explain
Briefly about its use, I leave you here only explained the class string (this time more
deepened).
In the next class, I intend to explain more advanced concepts, such as iterators and containers, for
could you explain a few more components of STL
[Link]

Strings
I started to talk about the class [Link] 12However, I only talked about how to start an object.
from the string class (and print it on the screen through docout). Now I will talk about some useful methods
inside the string class.
#include <iostream>
#include <string>
using namespace std;

int main()
{
string str1;
string str2;
string str3;

Welcome

if ([Link]()) // it is to be expected that it is empty...


{
The string 2 is empty!
}

int size = [Link](); //returns the length of str1

The string 1 has

Enter your name:


cin >> str2;

str3 = str1 + " " + str2;


str3 will be equal to str1, plus a space, plus str2

size = [Link]();

[Link](size, ", are you enjoying the program?"); //insert at the end

cout << str3 << endl;

size = [Link](); //the size of the name

Enter another name:


cin >> str2; //uses str2 to store another name

[Link](10, size, str2);


//replace the name. Starts at position 10 (after "Welcome ") and
prolongs
during the length of the name (that is, replace the name :P)

[Link](0, 10); //removes the first 10 characters (the phrase "Welcome


")

cout << str3 << endl;


[Link]

int pos = [Link]("gostar");


search for the first occurrence of "like" in str3 and return the position of it
1st character.

I like to be in position

str1 = str3; //str1 will take the value of str3

it is to be expected that yes


{
str1 and str3 are equal!
}

[Link]();
[Link]();
return 0;
}

Example 18.9 - Example of various methods of the string library


I ended up covering a lot of material, but let's take it easy.

string::empty()
If the string is empty, return true (1). If it is not empty, return false (0).

string::size()
Returns the number of characters that the string has.

string::operator +
We can concatenate two strings using the addition operator (+). I think by the example you all...
they saw how it worked.

string::insert()
Inserts a string into another string, starting from the position that we specify. Its definition is:
string& insert(size_type pos, const string& str);
At what position will the string to be inserted be placed.
PS: The variable type size_type is equivalent to unsigned int.

string::replace()
The method replace() substitutes a substring (a string within another string) for another string.
your definition is this:
string& replace(size_type pos, size_type n, const string& str);
What is the position of the beginning of the substring we want to delete, right? The number of characters that
we want to replace the astringent stress that we want to put.
[Link]

string::erase()
Turn off a substring within the string. The definition is:
string& erase(size_type pos=0, size_type n=npos);
From which position do we want to erase (if we do not specify anything, it is from the
first character) in the number of characters we want to delete (if we don't specify anything, it deletes
until the end of the sentence).

string::find()
size_type find (const string& str, size_type pos=0) const;
size_type find(char ch, size_type pos=0) const;
Search for the first occurrence of the substring str (or the character ch), starting from the position pos (which is 0
if we don't put anything, from the beginning).
End of lesson 18 of C++:
Next classC++ 19 - Advanced C++ Techniques - Part 3
Download thesource codetwo examples from the class
Download the class in PDF (Coming Soon)

Go to the top of the page

Class 19 - Advanced C++ Techniques - Part III


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

data structure, with the aim of providing the programmer the most efficient way to
store data
-vector, a data structure from the STL, similar to an array, but allows for expansion and
decrease in your capacity
linked list, a data structure that allows for efficient insertion and deletion of data,
through the use of pointers and dynamic memory

Data structures
In this lesson, I will focus on the study of data structures. The purpose of data structures is to
provide the programmer with the most efficient way (in terms of speed, memory) to
[Link]

store data. This data can be the HP of a character, or the textures of a level
game. A game developer needs the highest speed and memory they can obtain and,
yes, knowing how to implement data structures is fundamental.
Fortunately, there is the STL that generically implements a large part of the data structures.
more useful. With many years of development, it is almost impossible to do better than the STL
for generic data. However, the STL may not be the best solution in certain cases,
but in most of them it is the best available solution.

Limitations of an array
Let's suppose we need an array of a certain structure (Monster) that contains
all the monsters on the screen. How the number of monsters at the same time can vary throughout the
program, we can choose to allocate space for, let's say, 10 monsters (we are setting this
number as the maximum number of monsters that our array can handle). This is implemented.
in the following code:
#include <iostream>
using namespace std;

struct Monster
{
int hp;
int mp;
};

int main()
{
const int MAX_MONSTERS_SCREEN = 10;
Monster monstros_screen[MAX_MONSTERS_SCREEN];

//...
}

This would be a reasonable solution if we were certain that we would never exceed the limit of 10.
monsters on the screen. Let's imagine that we did some tests and found that at a certain level of the
In our game, there could be up to 1000 monsters on the screen. We could define the maximum capacity of the
array for 1000. However, this method can create a huge load on the program. The structure
Monster requires 8 bytes of memory (because it has two variables of the pointer type, each 4 bytes)
each), that is, the array would need 8000 bytes, which is almost 8 KB (KiloBytes). This seems
little, but that is because our structure only has 2 variables. If our data structure
If it occupied 1 KB, we would need almost 1 MB just to store this variable. This value is too much.
elevated to a variable, especially considering that it will only require so much
space at a certain level, but even so it will occupy this space for the entire time of
execution of the program.
There are several solutions to this problem. First, we will look at a very simple implementation.
(a class made by me) and another implementation much better (through the use of the vector class of
STL)

BetterArray Class
I decided to create a class that allows the addition (and deletion) of new elements in an array, through
of the use of pointers and dynamic memory. In addition, it has a counter, which also
[Link]

it can facilitate the counting of elements. This class only works with point type variables, but
we could use templates to become a generic class.
#include <iostream>
using namespace std;

class BetterArray
{
public
void addValue(int value); //adds a value to the end of the array
void delEndValue(); // removes the value at the end of the array

int getValue(int index); //returns the value that is at the position index of
array
int getCount(); //returns the number of elements in the array

BetterArray(); //constructor
~BetterArray(); //destructor

private

int *array; //the pointer to the array


int count; //o número de elementos do array
};

int main()
{
BetterArray test; //creates a test object for our class
[Link](3); //the value '3' is added to the end of the array
(primeiro valor)

this is a simple way to present the data within the array...


for (int x = 0; x < [Link](); x++)
{
cout << "Position: " << x << ", Value: " << [Link](x) << ",
Count: " << [Link]() << endl;
}

[Link]();

[Link](9);
[Link](27); //two values were added

for (int x = 0; x < [Link](); x++)


{
cout << "Position: " << x << ", Value: " << [Link](x) << ",
Count: " << [Link]() << endl;
}

[Link]();

[Link](); //a value was removed from the end of the array

for (int x = 0; x < [Link](); x++)


{
cout << "Position: " << x << ", Value: " << [Link](x) << ",
Count:
}
[Link]

[Link]();
return 0;
}

BetterArray::BetterArray()
{
array = NULL; //at the beginning the pointer to the array does not point to
nothing
count = 0; //number of elements is equal to 0
}

void BetterArray::addValue(int value)


{

int *tempArray = new int [count+1]; //creates an array in dynamic memory, with
more of an element than the old one

for (int x = 0; x < count; x++)


{
tempArray[x] = array[x]; //passes the contents of the old array to the
new
}

tempArray[count] = value; //o último elemento do array novo é alterado, com


the new value
count++;

delete [] array; //the old array is deleted


array = tempArray; //the pointer to the array now points to the new one
array
tempArray = NULL; //we no longer have use for this array

void BetterArray::delEndValue()
{
if (count > 1) //if there is more than one element...
{
int *tempArray = new int [count-1]; // creates a new array with one less
element of what was before

for (int x = 0; x < count-1; x++)


{
tempArray[x] = array[x]; //passes all elements (except for the
last) for the new array
}

count--;

delete [] array;
array = tempArray;
tempArray = NULL;
}
else if (count == 1) //if there is only one element, it is removed...
{
delete [] array;
array = NULL;
[Link]

count = 0;
}
}

int BetterArray::getValue(int index)


{
if (count > 0) //this is to prevent programmer errors
{
if (index < count)
{
return array[index];
}
}
}

int BetterArray::getCount()
{
return count;
}

BetterArray::~BetterArray()
{
if (array != NULL) //if the array has not been deleted yet...
{
delete [] array;
array = NULL;
}
}

Example 19.1 - BetterArray Class


This class requires a reasonable understanding of how pointers and memory work.
dynamic. I advise you to review theclass 11and toclass 14.

STL - Vector
The class I developed has many problems. First, because it only lasted about half an hour.
of development. Second, because it was developed by an 'amateur' student. In addition to these
problems, the most visible is the creation of a temporary array just to make the transition between the array
old and the new, that is, for a few moments, we will need double the memory, not to mention
talk about the processing time we need to transfer each element to the new array.
Fortunately, there is the vector class, which is part of the STL and is designed to introduce a new
data structure, similar to an array, but much more dynamic. We can declare a vector
through the following expression:
#include <vector>

vector <DATA_TYPE> identifier;

As an example, I will take advantage of the main that I made for the BetterArray class:
#include <iostream>
#include <vector>
using namespace std;

int main()
[Link]

{
vector <int> test; // creates a test vector, of type int
teste.push_back(3); //the value '3' is added to the end of the array
(first value)

let's note the differences


for (int x = 0; x < [Link](); x++)
{
cout << "Position: " << x << ", Value: " << teste[x] << ", Count: " <<
[Link]() << endl;
}

[Link]();

teste.push_back(9);
test.push_back(27); //two values were added

for (int x = 0; x < [Link](); x++)


{
cout << "Position: " << x << ", Value: " << teste[x] << ", Count: " <<
[Link]() << endl;
}

[Link]();

test.pop_back(); //a value was removed from the end of the array

for (int x = 0; x < [Link](); x++)


{
cout << "Position: " << x << ", Value: " << teste[x] << ", Count: " <<
[Link]() << endl;
}

[Link]();
return 0;
}

Example 19.2 - Tests with the vector class


Iwillexplaineachnewmethod,onebyone:

vector <int> test;


Here we are declaring a vector. The vector class makes use of templates to be able to handle
any type of variable. When we put <int> in the middle of the declaration, we are telling the class
we intend to use integer variables within the vector.

push_back(value) and pop_back()


The vector class uses the data structure concept of a 'stack'. This basically
It means that we can add new elements to the end of the stack and also remove elements from it.
stack end: the last to enter are the first to exit.
Push adds elements and pop removes elements. This concept can be illustrated in the
following figure (taken from thewikipedia):
[Link]

size()
The vector class has a counter that tells us the number of elements in the vector. How can we
Yes, it is quite useful.

Other situations with the vector class


There are still more features of the vector class to talk about, so that they can replace yours.
arrays in favor of this data structure. Fortunately, they are concepts quite easy to learn.
In the following example, we will see that using the vector class and using an array can be practically
same
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector <char> name; //this is something strange, because a string would be much
better

nome.push_back('I');
nome.push_back('V');
name.push_back('O');

cout << name[0] << name[1] << name[2] << endl;

name[0] = 'M'; //we can change each element like a normal array
nome[1] = 'A';
nome[2] = 'R';

cout << name[0] << name[1] << name[2] << endl;

[Link](5); //we can change the size of the array!

//if we did not do resize(), this would give an error...


name[4] = 'A'; //I am entering the characters in reverse...
nome[3] = 'I';

for (int x = 0; x < [Link](); x++)


{
cout << name[x];
}

cout << endl;

[Link]();

return 0;
}

Example 19.3 - More tests with the vector class


[Link]

In this example, the advantage of the vector over the array is obvious, maintaining its simplicity.
code.
There are still other methods that allow us to insert elements into the middle of each vector (instead of
only at the end). However, due to the nature of the vectors, these methods are very
inefficient, that is, if it is really necessary they will have to look for another alternative.

Linked Lists
Linked lists offer a huge advantage over vectors: they allow for the addition or
deletion of any element from the list, without losing performance. As not everything is perfect,
they have a huge disadvantage compared to vectors: it is not possible to access an index
random from the list, without losing performance. We will see why when analyzing the nature of a
linked list.
A list is composed of several nodes. Each node contains:
• a variable for the type of data we intend to store (e.g.: int value)
• a pointer to the next node (e.g., Node* next)
Note:

There are several types of lists, in this lesson I will present the simplest one, the simple list.
linked, which only has a pointer to the next element, with the last element
it is linked to a null value.
The other types of lists include a pointer to the previous element (doubly linked lists)
where the last element is linked to the first, forming a cycle (circularly linked list)
You can see a diagram illustrating a singly linked list (again from thewikipedia)

To visualize the concepts that are the foundation of a linked list, before creating a class for
the management of it, I will create an example of a linked list "by hand".
#include <iostream>
using namespace std;

class Node //each node of our list


{
public
int value; //the value that is stored
Node* next; //a pointer to the next node (that is linked to
this)

Node () { value = 0; next = NULL; } //a constructor to prevent


initialization errors
};

int main()
{
Node *um = new Node(); // this is how we are calling the constructor of each node
Node *two = new Node();
Node *three = new Node();

um->value = 1; // now we assign each value to each node


dois->value = 2;
[Link]

tres->value = 3;

node 'one' connects to node 'two';


two->next = three; //the node 'two' connects to the node 'three'
three->next = NULL; //the "three" node does not link to any, because it is the last
from the list

Node* temp = um; //to traverse the list, we link a temporary node
to the first on the list

while (temp != NULL) //while the temporary value is not null (not
reaches the end of the line)
{
cout << temp->value << endl; //shows us the value
temp = temp->next; //temp takes the value of the next
no, thus going through the list
}

[Link](); //we wait a bit...

now let's "eliminate" the second value

one->next = three; // see how simple it is! just point the 'one' node to the 'node'
three and that's it!
delete two; // now we remove "two" from memory because it already
we don't need him
two = NULL; //this is to prevent errors

temp = um; // we do everything again...

while (temp != NULL) //while the temporary value is not null (not
reaches the end of the line
{
cout << temp->value << endl; //shows us the value
temp = temp->next; //temp takes the value of the next
no, going through the list like this
}

[Link]();

delete one, three; //don't forget to delete!

return 0;
}

Example 19.4 - Rudimentary example of a linked list


Again, I will try to explain what is new (although nothing here is actually new, the
mechanics is what is new).
Let's start by analyzing the Node class. Each "Node" represents a node of the list, so a list is
a set of nodes. Each node has two variables:
• int value - This variable is used to store the value of each node (it is the variable "more
important" for the user)
• Node* next - This variable contains all the mechanics for a linked list to work.
It is a pointer to objects of the same class, that is, it serves to point to anotherNode.
[Link]

Thus, each node stores a variable that points to the next element, allowing the
access to other nodes of the list.
Note:

You certainly noticed the use of the expression NULL. This expression is commonly used to
identify pointers that do not point to any variable. In fact, the value NULL does
exactly the same effect as value0(zero). Instead of Node *next = NULL; we could
makeNode* next = 0;
Tip:

The node class also has a constructor. This constructor serves to ensure that the
variables are initialized with null values. If we do not define the variables, they will assume a
random value, which may cause conflicts later. This builder is not essential in this
for example, because I define the variables before using them, but in larger projects this small
a line of code can provide tremendous help.

For example, we could use the following code:

if (node == NULL)
{
Error
}
else
{
cout << node->value << endl;
}

After creating the class, we declare three pointers (with the creative names 'one', 'two' and
"three") and we allocated a Node type object in dynamic memory for each of them. At this point
I advised you to review theclass 14to remind them how dynamic memory works.

Role of pointers and dynamic memory in a list


As listas ligadas têm o propósito de facilitar a inserção e eliminação de cada nó. Como tal, é
bastante óbvio o papel da memória dinâmica e apontadores numa lista ligada. No exemplo acima,
to initialize the list, I followed the following steps:
• Assign the values of each node (value)
• I connected node "two" to node "one". This is done by assigning the object "two" to
pointer "next", which is within the node "one". Thus, we can say that the node that is to
Following node 'one' is node 'two'.
• I connected the knot 'two' to the knot 'three', using the same process as above.
• Set the pointer 'next' of the node 'three' to NULL. This means there are no more
elements in the list, that is, "three" is the last element of the list
To better understand the importance of pointers and dynamic memory, I demonstrated the
specific case of node elimination:
• I connected node "one" to node "three". I set the next pointer of node "one" to point to the
the "three" node (thus the "three" node becomes the next node after the "one" node)
• We remove the node "two" from dynamic memory, as it is no longer needed for the rest.
of the program (this step is not necessary, as the previous step already eliminates the
[Link]

list element. However, this step is highly advisable, as it will allow us to


free memory
We can see the ease with which we eliminate an element in a linked list: just change a
pointer in the node before the element we want to remove. The other elements remain
point to the next nodes, regardless of their location.

Go through the list


This is where the disadvantage of a linked list presents itself. In an array, each element is
organized in memory: the next element is always in the following position in memory. In a
linked list, each element can be located anywhere in memory, up to ten thousand places to
in front of or behind the following element. You will see this concept illustrated in the tables.
following:
Array
Address 1200 1201 1202 1203 1204
Value 1 2 3 4 5
Linked List
Address 1200 1201 1202 1203 1204 1205 1206 1207 1208
Value 4 --- 2--- --- 5 3 1
Next (Points to) 1204 --- 1205 NULL 1200 --- 1202
Note:

The "holes" (---) in some addresses in the linked list mean addresses that are occupied by
other variables and serves to illustrate the "disorder" of a list. In a program, these "holes"
they would also exist in an array (although before or after the entire array and never between each element
of the array). This note is just to prevent the impression that lists take up more memory than
an array (in fact, they occupy, as they have one more variable than an array: a pointer. In
meanwhile this increase is negligible.
As such, it is much easier (and more efficient) to access an element of an array than an element of
a list. This is because, if we want to access the fourth position of an array we do array[3] (or
array+3). With this instruction, the 3rd element to the right of the first will be searched for. To access it
to access the fourth element of a list we would have to do: head->next->next->next, in which
head the first element of the list. So far we haven't lost much in efficiency, but if we want to
consulting the x element of a list, the case changes. Meanwhile, in an array it would be so
simple as array[x], in a list we would have to resort to something like:
int getValue(int x, Node* head)
{
Node* temp = head;
for (int i = 0; i < x; i++)
{
temp = temp->next;
}

return temp->value;
}

The simple use of 'for' makes this much more inefficient than a simple array[3];
[Link]

Class List
Since this lesson has already been very long (and because the code for a List is a bit large), I decided
put the class list together with thesource code of this class, instead of taking up even more space on this
page. I think it's easy to understand, at least if you understood the code above (and it's very
commented).
Even covering so many aspects of these simple data structures, this still isn't enough. In
In the next class, I will introduce the concept of an iterator and I will show the List class from the STL. I hope
you can also introduce the data structure 'binary tree', as well as some algorithms
search simples.
End of class 19 of C++:
Next classC++ 20 - Advanced C++ Techniques - Part 4
Download thesource codetwo examples from the class
Download the class in PDF (Coming soon)

Go to the top of the page

Class 20 - Advanced C++ Techniques - Part IV


<!--
google_ad_client = "pub-9639791948153775";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="3703014365";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "000000";
google_color_text = "000000";
Key Concepts:

-iterator, a variable that allows traversing the elements of a container, in an abstract manner and
generic
-list, a data structure of the STL, that has a mechanism identical to a doubly linked list
connected
-preprocessor, a component of C++ that processes the received text and includes its
results in the same file

Iterators
Before moving on to the class list of STL, it is important to know how to work with iterators. So far
we have been using the indexing operator ('[]') to obtain the values of the variables within the vectors,
as we did with the arrays. The STL discourages this way of accessing the elements of its
containers (a container is an object that serves to hold other objects, such as class)
vector list in STL). It encourages the use of iterators, which are very similar to
indicators. In theclass 14we analyze the similarities between a pointer and an array:
#include <iostream>
[Link]

using namespace std;

int main()
{
int *array_pointer = new int[5]; //creates a new array in dynamic memory

int *array_begin = array_pointer;


/* We created a pointer and then assigned it the address of the array that
we created earlier.
Don't forget that the array_pointer points to the first element of the 5
variables that we create in dynamic memory.
Thus, the variable array_begin is pointing to the first element
from this array, that is, it marks the beginning of it.
*/

int *array_end = array_pointer + 5; //using the same logic, the array_end


points to the 5th element of the array (last)

int *array_iterator; // this is our iterator, the pointer that will


traverse the array

/* This part is explained below (outside the code) */

for (array_iterator = array_begin; array_iterator != array_end;


array_iterator++
{
*array_iterator = 10; //only used to fill the array with the value 10
}

for (array_iterator = array_begin; array_iterator != array_end;


array_iterator++
{
cout << *array_iterator << endl; //shows the values
}

[Link]();

delete [] array_pointer; //deletes the array from dynamic memory

return 0;
}

Example 20.1 - Primitive example of an iterator


Ufa, I admit that this code is not very easy to understand (besides there being other
much easier solutions to implement), but it is necessary for them to understand how
iterators operate within the STL. The entire mechanism revolves around operations with the address.
with pointers, so review itclass 14I will start by explaining what we need to
use an iterator:
• a pointer to the beginning of the "container" (in this case the array)
• a pointer to the end of the 'container'
• a pointer that traverses the 'container' from start to finish (the iterator)
In the example above, we used these components and implemented them through a for loop.
The first instruction given to for(array_iterator = array_begin) corresponds to initialization, or
[Link]

so, we are 'telling' the iterator where in memory it should start to traverse the
container.
In the second instruction, the test for the condition (array_iterator != array_end), we ask the computer
for, while the array_iterator is equal to the array_end (that is, while the iterator has not reached the
finally) process the instruction block (*array_iterator = 10) and to execute the third instruction, the
increment instruction (array_iterator++), which makes the iterator point to the
next element.
It was the best I could explain this mechanic, but any questions andcontact me

Iterator in a vector
To apply iterators to "real life," I will show the same example, but using vectors.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector <int> my_array;
vector <int>::iterator my_iterator; //ok, this notation is strange, but it works
sentido ;)

my_array.push_back(10); //let's take advantage of the conveniences of the vector!


my_array.push_back(20);
my_array.push_back(30);
my_array.push_back(20);
my_array.push_back(10);

for (my_iterator = my_array.begin(); my_iterator != my_array.end();


my_iterator++
{
cout << *my_iterator << endl;
}

[Link]();

return 0;
}

Example 20.2 - Example of an iterator in STL (vector class)

Why are iterators important?


In a class like vector, the iterators are not very important, because we can use the
operador '[]'. No entanto, em classes como a classelist(que iremos analisar de seguida), não
we will be able to access its elements randomly (with []), because it is a list
linkedsee the previous classThe STL presents another type of containers that cannot be accessed by the
its elements randomly and, therefore, they hypothesized the iterators in all their
containers. Iterators are the "official" way of the STL to traverse containers, because the
STL was made to be generic and abstract, that is, the programmer does not have to worry about
use different ways to access each container of the STL, because the iterators cover all
[Link]

these forms. Also, many methods within the STL take advantage of iterators, for example,
within the vector class we can use the following code to remove the first 2 elements
from an array:
my_array.erase(my_array.begin(), my_array.begin()+3);
Another thing that is important to note is that iterators differ slightly from container to
container. For example, while with the vector it is possible to do ([Link]() + 2), with the list it is
it is not possible (it is only possible to increment(++) and decrement(--)), therefore we cannot
reuse an iterator from a vector with a list.

Class list
If you have already worked with the vector class and understood at least the basics of iterators, then it goes
it's very easy to work with lists. One of the advantages of STL is that working with containers,
in terms of syntax and organization, they are very similar, differing only in what it is
even necessary. In this way, the choice of a container is not related to the ease of
use of it, but rather with its adaptation to our work. That is why the STL
it's so good :D.
#include <iostream>
#include <list>
using namespace std;

int main()
{
list <int> my_list;
list <int>::iterator my_iterator;

my_list.push_back(20); //we insert an element at the end of the list


(this is the same as the vector)
my_list.push_back(30);
my_list.push_front(0); //we insert an element at the beginning of the list
with no effort for the programmer and for the computer
my_list.insert(++my_list.begin(), 10); //we insert an element into
position 1 of the list (between 0 and 20)

This would already be impossible in a vector, without consuming many resources of the machine.

for (my_iterator = my_list.begin(); my_iterator != my_list.end();


my_iterator++)
{
cout << *my_iterator << endl;
}

[Link]();

return 0;
}

Example 20.3 - Simple example with the list class from the STL
I think the code is quite simple to understand and clearly highlights the differences between the vector and the
list.
Note:
[Link]

Surely you have seen me use the increment operator (++) before and after each
variable, for example i++ or i. There is a small difference between the two and it happens to be
important in this example (in the part of ++my_list.begin()).

Fazeri++ causes the instruction where oi++ is inserted to be executed first and only that.
only then does it increment the variable, while doing++if causes the variable to be incremented first
and only after execute the instruction where ++i is inserted. With an example it is easy to understand:

int i = 3;
cout << i++; // the value displayed will be '3'
cout << i; the presented value will be '4'
cout << ++i; // the value displayed will be '5'

This comes in reference to the instruction++my_list.begin(), which I accidentally wrote


my_list.begin()++ and that, therefore, had no effect (try using it this way)

Accessing the elements of a list


As I have explained, it is not possible to do my_list.begin()+2 to access the 3rd element of a
list (don't forget that my_list.begin() is the first element and therefore, when we add 2,
he moves to the 3rd and not to the 2nd!). However, it is possible to make increments to an iterator until
to reach this value. Of course, this takes longer than random access to the vectors, but
I have already explained the advantages and disadvantages of lists inprevious classThe container list presents the
mechanics of a doubly linked list, therefore it allows us to traverse its elements to
forward (iterator_list++) or backward (iterator_list--). Keep this example quite
simple
#include <iostream>
#include <list>
using namespace std;

int main()
{
list <int> my_list;
list <int>::iterator my_iterator;
int e; //used for user selection

my_list.push_back(10);
my_list.push_back(20);
my_list.push_back(30);
my_list.push_back(40);
my_list.push_back(50);
my_list.push_back(60);

my_iterator = my_list.begin();

cout << "Which element of the list do you want to access? [0-5]: [ ]\b\b";
//o \b is the special character for backspace, that is, it positions the cursor back 2
characters before where it is supposed to be
It gives a more pleasant effect :)
cin >> e;

for (int x = 0; x < e; x++)


{
[Link]

my_iterator++;
}

cout << "Value: " << *my_iterator << endl;

[Link]();
[Link]();

return 0;
}

Example 20.4 - Accessing values of a list 'randomly'

The preprocessor in C++


The preprocessor in C++ causes a given text to be processed and inserted into
document. It is something quite simple to use and was frequently used in C, but now it is already
it contains something outdated. However, quite a few programmers still use it and it is important.
to meet him. All preprocessor commands start with a '#'.

#include
This is the most used command in C++ and does amazing things. Basically, it copies all the code from
a certain file to the file in which this instruction is present, which causes the
the code becomes much prettier and organized. It can be used in two ways:
#include <file.h>
for system files, like iostream, etc.
#include "file.h"
for files created by you.

#define
The #define substitutes 'words for numbers', acting as a constant. For example:
#define PI 3.14159
Replace all "words" PI within the code (except those inside strings) with the value
3.14159. It is still widely used, but discouraged, because in C++ there is the const type, which
works much better.
It is also possible to use defines as a function (this is called a macro).
example:
#define sum(a,b) a+b
Again, declaring functions inline has the same effect, and it's much better (inline int sum
(int a, int b) { return a+b; }
Tip:

Declaring a class as inline causes all calls to that function to be replaced


by the same code. For example, with the above sum function, the codesoma(3,7) would be
replaced by 3+7. With this, there is a gain in processing speed, but a loss in
[Link]

program size. Small functions (like the sum function) are recommended to be
declared as inline, but more complex functions are not!

#ifdef, #ifndef, #endif


These are useful in headers and in specific cases (like for debugging and so on). The #include is not.
perfect, one of its limitations is not checking if a certain file has already been included in
program, in order to prevent it from being included more than once. The #ifndef allows us to
artificially verify this:
#ifndef FILE_ALREADY_INCLUDED //if it has not been defined yet
(that is, if the file has not been included yet)
#define FILE_ALREADY_INCLUDED
// código aqui
#endif
Another interesting thing is, for example, a check of the operating system:
#ifdef WINDOWS
#include "headersparawindows
#endif
#ifdef LINUX
#include "headersparalinux
#endif
This could be used for other cases, like a debug mode, where we would just need to write
#define DEBUG_MODE and the program recompiled to provide us with detailed instructions of
how each element of the game is behaving.

And now?
The theoretical C++ classes on this site have already ended! For the website followers, they can stay
rested, there are still 5 more practical classes planned, which will show how to build (well) a
game. The game will continue to be text-based, but I think you will be happy with the
result!
However, there is still much to be a "master" in C++ (which I am far from being). There is
enough information on the Internet and in good practice books in C++, as well as more
algorithms, data structures, and a lot of advanced C++. However, I think the foundations are already
Given, and the rest will come as "additions" to your capacity. I leave you some websites and books.
for self-study material (mostly in English, unfortunately):

Books
• Programming in C++ - Basic Concepts and Algorithms, various authors - Book in
Portuguese that serves as an introduction to C++FCA, FNAC, Bertrand)
• Effective C++, Scott Meyers - 55 dicas para melhorar a vossa forma de programar em C++
([Link], [Link] )
• More Effective C++, Scott Meyers - The continuation of the previous one, with 35 more tips
([Link], [Link] )
• Effective STL, Scott Meyers - 50 tips to improve your programming style with the
STL ([Link], [Link] )
• C++ for Game Programmers, Mike Dickheiser - A book that shows the programmer with
[Link]

experience in C++ how to use it to program [Link], [Link] )


• Beginning C++ Game Programming, Michael Dawson - Teaches C++ to beginners
drawing on examples from [Link], [Link] )
• Design Patterns: Elements of Reusable Object-Oriented Software, various authors - This book
teach us how to implement the best ways to approach certain problems, through the
OOP ([Link], [Link] )

Websites
• C++ Tutorial by Pedro Santos
• C++ Language Tutorial
• [Link]
• SGI - STL Programmer's Guide
• C++ Reference
And last but not least, websites with plenty of resources (including forums) that
they will help a lot (they helped me a lot and I have a special debt to them):
• [Link] (English)
• Gamedev-PT (Portugal)
• PDJ (Brazil)
• Unidev (Brazil)
End of class 20 of C++:
Next class -> C++ P1 - Making a game from start to finish - Part 1
Download thesource codetwo examples from the class
Fazer o download da aula emPDF(Brevemente)

Go to the top of the page

You might also like