Learn C++ Basics for Game Development
Learn C++ Basics for Game Development
html
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]
#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.
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.
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
**********************************/
**********************************/
#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
return 0;
}
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
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.
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
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]
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;
}
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]
int main()
{
int number = 8; //choose any number
int attempt; //the user's attempt
[Link]();
[Link]();
return 0;
}
-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:
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;
}
c = a + b; -The variable c becomes the sum of the variable a and the variable b.
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;
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]
-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;
[Link]();
[Link](); // Stops the program until the user presses a key
return 0;
}
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
Enter a HP value:
cin >> hp;
cout << "The test is equal to " << varteste << endl;
[Link]
[Link]();
[Link](); // Stops the program until the user presses a key
return 0;
}
int main()
{
bool varteste; //the variable for verification
int hp; //health points
Enter a HP value:
cin >> hp;
[Link]();
[Link](); // Stops the program until the user presses a key
return 0;
}
int main()
{
int hp; //the health points
[Link]();
[Link](); // Pauses the program until the user presses a key
return 0;
}
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]
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).
int main()
{
int hp; //the health points
Enter a HP value:
cin >> hp;
[Link]();
[Link](); // Pauses the program until the user presses a key
return 0;
}
int main()
{
int choice;
GAME MENU
1 - New Game
cout << "2 - Load Game" << endl;
cout << "3 - Options" << endl;
cout << "4 - Exit" << endl;
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;
}
If the value is not equal to 4 (therefore different from the other values above),
Wrong choice
int main()
{
int number = 6;
int user;
if (user == number)
{
CONGRATULATIONS!!!! YOU GOT IT RIGHT
}
[Link]();
[Link]();
return 0;
}
int main()
{
int choice;
GAME MENU
1 - New Game
cout << "2 - Load Game" << endl;
3 - Options
4 - Exit
if (choice == 1)
[Link]
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;
}
int main()
{
int choice;
GAME MENU
1 - New Game
cout << "2 - Load Game" << endl;
3 - Options
4 - Exit
switch (choice)
{
case 1: // if the choice is 1
[Link]();
[Link]();
return 0;
int main()
{
int 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;
[Link]();
[Link]();
return 0;
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
{
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]
return 0;
}
Instead of using
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)
int main()
{
{
Welcome to this annoying program (version 2).
If you want to exit, press * followed by ENTER
return 0;
}
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;
}
int main()
{
int x = 0;
}
[Link]
[Link]();
return 0;
}
int main()
{
for (int x = 0; x < 5; x++)
{
cout << "X is equal to " << x << endl;
}
[Link]();
return 0;
}
int main()
{
int a;
int b = 10;
bool greater;
if (a <= b)
{
maior = false;
}
else
{
maior = true;
}
[Link]();
[Link]();
return 0;
}
int main()
{
int a;
int b = 10;
bool maior;
Enter a number:
cin >> a;
[Link]();
[Link]();
return 0;
}
int main()
{
int number = 21; //the number to be guessed
[Link]
cout << "Welcome to version 1.1 of the GUESS THE NUMBER game" << endl;
while (!done)
{
Enter your attempt:
cin >> value;
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
}
[Link]();
[Link]();
return 0;
}
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:
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;
}
int createCharacter()
{
Character Created. Name: Agnor
return 0;
}
int main()
{
createCharacter();
criarPersonagem();
createCharacter();
[Link]();
return 0;
}
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;
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);
return 0;
}
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]
return 0;
}
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;
[Link]();
[Link]();
return 0;
}
[Link]
int main()
{
int a, b;
[Link]();
[Link]();
return 0;
}
/*FUNCTION DEFINITIONS*/
[Link]
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()
/***********************************************************
int getRandom(int from, int to)
generates random numbers that range from "from" to "to"
***********************************************************/
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;
}
#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 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;
}
numeroTentativa = escolha + 1;
[Link]
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;
}
inGame();
}
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:
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:
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];
}
[Link]();
[Link]();
return 0;
}
int main()
{
int MAX_ELEMENTS = 10; //the maximum number of elements in the array
[Link]();
[Link]();
return 0;
}
int main()
{
int MAX_ELEMENTS = 5; //the maximum number of elements in the array
[Link]();
[Link]();
return 0;
}
of writing.
int main()
{
int MAX_CHARS = 30;
char name[MAX_CHARS];
Hello,
[Link]();
[Link]();
return 0;
}
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)
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
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.
}
[Link]();
return 0;
}
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.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.
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]
[Link]();
return 0;
}
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]");
cout << welcome << " " << name << ", " << age << " years" << endl;
system("PAUSE");
return 0;
}
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;
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;
}
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:
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:
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]
struct Character
{
int hp, mp; //podem fazer isto; explicação abaixo.
int main()
{
different ways to fill the variables:
Personagem Nillight = { 30, //HP
10, //MP
};
Personagem Laveius = { 50, 7 };
Nysker character;
HP of Nillight is
[Link] << endl;
HP of Laveius is
<< endl;
HP of Nysker is
endl;
[Link]();
return 0;
}
struct Square
{
[Link]
int side;
int area;
};
int main()
{
Square square;
[Link] = 4;
[Link] = calcularArea(square);
cout << "Area of the Square: " << [Link] << endl;
[Link]();
return 0;
}
#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
{
/////////////////////////////////////
///////////Variables/////////////////
/////////////////////////////////////
/* *
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);
int main()
{
gameMenu();
[Link]();
return 0;
}
callBattle(monster);
Call a Battle for a specific monster (e.g., callBattle(SHADOW);
)
*/
[Link]
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;
}
{
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;
}
srand(GetTickCount());
int random = ( rand() % ate ) + de;
return random;
}
lost :(((((
int lost()
{
You lost... Next time you will have better luck :(
gameMenu();
return 0;
}
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]
int gameMenu()
{
int choice;
Choose an opponent:
1 - Orc
2 - Lizard
3 - Shadow
4 - Bahamut
5 - LAST
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;
}
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
int func();
int main()
{
[Link]
return 0;
}
int func()
{
int z = 10; //local variable, can only be used in the function func()
return x;
}
void function();
int main()
{
function();
[Link]();
return 0;
}
void function()
{
int y; //declare a variable inside the function();
[Link]
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:
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
}
Let's imagine that we are looking at the computer's memory (from address 93 to 107):
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 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]
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
}
Notice:
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)
int main()
{
int i;
int &i_ref = i;
i = 20;
i_ref = 10;
Variable i:
Reference for i:
[Link]();
return 0;
}
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;
swap(a, b);
A:
cout << "B:" << b << endl;
[Link]();
return 0;
}
int main()
{
int var = 30;
cout << "Address of variable var: " << &var << endl;
cout << "Value of the variable var: " << var << endl;
[Link]();
return 0;
}
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
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;
}
Variablex:
Valor de x: 20
Address of x: 0x22ff74
Pointer variable:
int main()
{
int x = 10;
int *pointer = &x;
x += 10;
Value of X:
cout << "Value pointed by pointer: " << *pointer << endl;
*pointer += 10;
Value of X:
cout << "Value pointed by pointer: " << *pointer << endl;
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;
int main()
{
int a = 20;
int b = 10;
A:
cout << "B:" << b << endl;
[Link]();
return 0;
}
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)
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
nome[5] = 's';
nome[6] = ' '; //espaço
nome[7] = 'H';
nome[8] = 'Q';
return 0;
}
int main()
{
char *name = "agnor";
nome = "Agnor";
return 0;
}
[Link]
int main()
{
example
char dest[8]; //creates a variable with the same number of characters as the string
[Link]();
return 0;
}
Program:
int main()
{
example
[Link]();
return 0;
}
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.
String1:
cout << "String2: " << String2 << endl;
cout << "String3: " << String3 << endl;
String4: String4
[Link]();
return 0;
}
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");
[Link]();
return 0;
}
Example 12.6 - Display one letter at a time with the string class
[Link]
*********************************/
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
Function declaration
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);
int main()
{
bool done = false;
switch (menu_choice)
{
case 1:
new_game(); //a new game starts
break;
case 2:
done = true; //exit the game loop
}
}
[Link]();
return 0;
}
Function Definition
return false;
}
return false;
}
int menu()
{
int choice;
Choose an option:
1 - New Game
cout << "2 - Exit\n" << endl;
return choice;
}
void won()
{
Congratulations! You won the game!
[Link]();
[Link]();
}
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 '-'
return false;
}
void new_game()
{
srand(GetTickCount());
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
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!
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.
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;
};
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
private
public
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
private
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;
}
private
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);
private
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.
class Point
{
public
void changeX(int u_x) { x = u_x; }
void changeY(int u_y) { y = u_y; }
[Link]
private
int main()
{
Point point; // we declare an object point of the Point class
[Link](7);
[Link]();
return 0;
}
[Link] = 50;
[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]
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:
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
do something....
delete pointer;
Simple, but its forgetfulness is the cause of many serious program errors.....
Note:
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:
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();
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]
Variable x:
Valor de x: 20
Address of x: 0x434000
Variable y:
Valor de y: 10
Address of y: 0x434004
Pointer variable:
Variable x:
Valor de x: 20
Address of x: 0x434000
Variable y:
Value of y: 10
Endereco de y: 0x434004
Pointer variable:
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.
int array[10];
int *pointer;
int main()
{
pointer = array;
array[0] = 50;
array =
cout << "pointer = " << *pointer << endl;
[Link]();
return 0;
}
int array[10];
int *pointer;
int main()
{
pointer = array;
array[7] = 50;
array =
pointer =
[Link]();
return 0;
}
int array[10];
int *pointer;
int main()
{
pointer = array;
array[0] = 50;
array =
pointer =
[Link]();
return 0;
}
[Link]
int array[10];
int *pointer;
int main()
{
pointer = array;
array[7] = 50;
array =
pointer =
[Link]();
return 0;
}
int main()
{
int array[2];
int *pointer;
pointer = array;
array[0] = 0;
pointer[1] = 1;
[Link]();
return 0;
}
(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 main()
{
const int SIZE = 10; //constant variable
int array[TAMANHO];
list[0] = 4; //just to test if the array has been cleared
clear_array(list, SIZE);
[Link]();
return 0;
}
int main()
{
int size;
Enter a size for the array (less than 1000, and only one
suggestion) << endl;
cin >> size;
clear_array(list, size);
[Link]();
[Link]();
return 0;
}
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
//calculation functions
int area() { return width * height; }
int perimeter() { return (width * 2) + (height * 2); }
private
class Rectangle
{
public
//calculation functions
int area() { return width * height; }
int perimeter() { return (width * 2) + (height * 2); }
private
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;
}
//...
(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 main()
{
Point a, b, c;
a.x = 10;
a.y = 5;
b.x = 10;
b.y = 15;
cout << "C.x = " << c.x << " and C.y = " << c.y << endl;
[Link]();
return 0;
}
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 main()
{
Point a, b;
a.x = 10;
a.y = 5;
b = a;
A: X =
B: X =
[Link]();
return 0;
}
class Rectangle
{
public
//calculation functions
int area() { return width * height; }
int perimeter() { return (width * 2) + (height * 2); }
private
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
//calculation functions
int area() { return width * height; }
int perimeter() { return (width * 2) + (height * 2); }
private
#endif
#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);
[Link](5);
[Link]();
return 0;
}
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)
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
private
int strength; // the character's strength.
};
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
};
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
private:
int strength; // the character's strength.
};
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
};
void attack();
private
int strength; // strength with which the Orc attacks.
};
int main()
{
Human we;
[Link]
Magic magician;
Orc orc;
[Link]();
[Link]();
[Link]();
[Link]();
}
Each class has its own constructor and destructor, that is, a generalized class cannot
inherit the constructor of the superclass.
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
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;
}
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
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
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.
};
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
};
void attack();
private
int strength; // strength with which the Orc attacks.
};
int main()
{
Human, human;
Magical mag;
Orc orc;
speak(&orc);
[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
private
int strength; // the character's strength.
};
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
};
void attack();
private
int strength; // strength with which the Orc attacks.
};
int main()
{
Humanoid hum;
Magical mag;
Orc orc;
speak(&orc);
[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.
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;
int main()
{
area (2, 4); //the function int area will be called
[Link]();
return 0;
}
{
This is using the double area function
Area =
}
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 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]
f(int x = 0, y, z = 0);
It is not correct.
int main()
{
int array[5] = {2, 4, 5, 2, 1}; //creates an array of 5 integers
[Link]();
return 0;
}
return value;
}
from this processing the array will remain changed (unlike variables, which can only be
altered through references and pointers).
#include <iostream>
using namespace std;
int main()
{
int array[5] = {2, 4, 5, 2, 1}; // creates an array of 5 integers
Array normal:
duplicate(array, 5);
[Link]();
return 0;
}
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;
[Link]();
return 0;
}
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
private
char *name;
};
int main()
{
Orc monster("Orc");
Monster spider("Spider");
Monster goblin("Goblin");
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
int main()
{
int x = Math::add(4, 5);
int y = Math::divide(20, 4);
int z;
Math m;
cout << "X: " << x << ", Y: " << y << endl;
[Link]();
return 0;
}
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 main()
{
int (*calculator)(int a, int b); // we created a pointer to a function
X: x, Y: y
[Link]();
return 0;
}
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 main()
{
int x = calculator(4, 6, add);
int y = calculator(4, 2, multiply);
X: x, Y: y
[Link]();
return 0;
}
return result;
}
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;
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;
}
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;
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;
}
Templates in classes
Templates can also be used in classes. As you may have noticed how it works,
[Link]
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;
}
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]
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;
}
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;
}
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
[Link]();
return 0;
}
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;
}
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
size = [Link]();
[Link](size, ", are you enjoying the program?"); //insert at the end
I like to be in position
[Link]();
[Link]();
return 0;
}
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)
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 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)
[Link]();
[Link](9);
[Link](27); //two values were added
[Link]();
[Link](); //a value was removed from the end of the array
[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
}
int *tempArray = new int [count+1]; //creates an array in dynamic memory, with
more of an element than the old one
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
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::getCount()
{
return count;
}
BetterArray::~BetterArray()
{
if (array != NULL) //if the array has not been deleted yet...
{
delete [] array;
array = NULL;
}
}
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>
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)
[Link]();
teste.push_back(9);
test.push_back(27); //two values were added
[Link]();
test.pop_back(); //a value was removed from the end of the array
[Link]();
return 0;
}
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.
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');
name[0] = 'M'; //we can change each element like a normal array
nome[1] = 'A';
nome[2] = 'R';
[Link]();
return 0;
}
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;
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();
tres->value = 3;
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
}
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
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]();
return 0;
}
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.
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.
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)
-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]
int main()
{
int *array_pointer = new int[5]; //creates a new array in dynamic memory
[Link]();
return 0;
}
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 ;)
[Link]();
return 0;
}
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;
This would already be impossible in a vector, without consuming many resources of the machine.
[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'
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;
my_iterator++;
}
[Link]();
[Link]();
return 0;
}
#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:
program size. Small functions (like the sum function) are recommended to be
declared as inline, but more complex functions are not!
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]
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)