Files
uni_notes/10 Courses/02 - SoSe 2026/OOP/29605581 - Classes.md
2026-04-16 12:25:30 +02:00

163 lines
2.5 KiB
Markdown

---
created: 2026-04-16 12:21
course: "[[29605397 - OOP]]"
topic: classes
related:
type: lecture
status: 🔴
tags:
- university
- cpp
---
## 📌 Summary
> [!abstract]
> Introduction of Classes and visibility modifiers
>
---
## 📝 Content
C approach of defining a Pokemon:
```C
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:
```C++
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:
```C++
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)
```c++
class Pokemon {
// ...
public:
void setExp() { /*...*/ }
int getExp() { /*...*/ }
}
```
### Constructors
Given the class:
```C++
class Pokemon {
private:
int exp;
int level;
}
```
We can create a new instance using the _basic constructor_:
```C++
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_:
```C++
class Pokemon {
// ...
public:
Pokemon(const Pokemon& other): exp(other.exp), level(other.level) {}
}
```