2.5 KiB
2.5 KiB
created, course, topic, related, type, status, tags
| created | course | topic | related | type | status | tags | ||
|---|---|---|---|---|---|---|---|---|
| 2026-04-16 08:01 | 29605548 - 29605397 - OOP | classes | lecture | 🔴 |
|
📌 Summary
[!abstract] Introduction of Classes and visibility modifiers
📝 Content
C approach of defining a Pokemon:
typedef struct {
int exp;
int level;
int attack;
int defense;
int speed;
int hp;
} Pokemon;
void upgrade(*Pokemon p, int gainedExp) {
p->exp += gainedExp;
if (p->exp >= 4000) {
p->exp -= 4000;
p->level += 1;
}
}
int main() {
Pokemon fukano = {3600, 1, 400, 400, 20, 1200};
printf("Exp of fukano: %d", fukano);
upgrade(&fukano, 400);
printf("Exp of fukano: %d", fukano);
return 0;
}
In C++ we use classes:
class Pokemon {
public: // visibility modifier
int exp;
int level;
int hp;
void upgrade(int gainedExp) {
exp += gainedExp;
if (exp >= 4000) {
exp -= 4000;
level += 1;
}
}
}
int main() {
Pokemon fukano = {3600, 1, 1200};
cout << "Exp of fukano: " << fukano.exp << endl;
fukano.upgrade(400);
cout << "Exp of fukano: " << fukano.exp << endl;
}
Scope Modifiers
If we want to hide data beyond the class itself we can use the private visibility modifier:
class Pokemon {
public:
string name;
private:
int exp;
int level;
int hp;
public:
void upgrade(int gainedExp) {
exp += gainedExp;
if (exp >= 4000) {
exp -= 4000;
level += 1;
}
}
}
int main() {
Pokemon fukano = {3600, 1, 1200};
fukano.upgrade(400); // this is OK
fukano.exp += 400; // this is not OK
}
Getters and Setters
Getters and Setters allow controlling the change like:
- ensuring a number is in a range
- update depending parameters (like level with exp)
class Pokemon {
// ...
public:
void setExp() { /*...*/ }
int getExp() { /*...*/ }
}
Constructors
Given the class:
class Pokemon {
private:
int exp;
int level;
}
We can create a new instance using the basic constructor:
class Pokemon {
// ...
public:
// Default constructor: allows Pokemon <name>; -> exp = 0, level = 0;
Pokemon(): exp(0), level(0) {};
// or
Pokemon(0, 0);
// Base constructor
Pokemon(int e, int l) {
exp = e;
level = l;
}
// or as
Pokemon(int e, int l): exp(e), level(l) {};
}
int main() {
Pokemon fukano(3600, 1);
}
We can also create an instance as a copy of another object of the same class:
class Pokemon {
// ...
public:
Pokemon(const Pokemon& other): exp(other.exp), level(other.level) {}
}