-
Notifications
You must be signed in to change notification settings - Fork 0
/
10-CLASSESinCpp.cpp
80 lines (61 loc) · 1.77 KB
/
10-CLASSESinCpp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
CLASSES in C++
Objects-Oriented Programming
A class contains all the data and variables for our defined class
Classes are types, so creating a class we are creating a new type
class Player {
int x, y;
int speed;
}; // IMPORTANT to put semicolon at the end of the brackets for the class (functions brackets didn't need them)
Player player;
here i created a variable called player of type Player
the variables made from classes are objects called INSTANCES
so player is an INSTANCE
player.x = 5;
This doesn't work because player can't access to x because x is a private memeber declared in the class Player
VISIBILITY
When you specify the visibility of the stuff inside the class: by default all the content of a class is provate: only visible to the functions present in the class. So only the functions inside that class can actually access those variables. If we want to access those variables from the main function we need to made them public.
class Player {
public:
int x, y;
int speed;
};
int main()
{
Player player;
player.x = 5;
}
Ex: we want to create a function that moves the playes
class Player {
public:
int x, y;
int speed;
};
void Move(Player& player, int xa, int ya)
{
player.x += xa * player.speed;
player.y += ya * player.speed;
}
int main()
{
Player player;
Move(player, 1, -1);
}
FUNCTIONS INSIDE CLASSES ARE CALLED METHODS
So we can put the functions that receive as input the data from the class inside that class and those functions are called methods
Ex
class Player {
public:
int x, y;
int speed;
void Move( int xa, int ya) [M]
{
x += xa * player.speed; [M]
y += ya * player.speed; [M]
}
};
int main()
{
Player player;
player.Move(player, 1, -1); [M]
}
So a class is composed by DATA and FUNCTIONS (methods) that can manipulate those data