Files
uni_notes/00 Inbox/29605321 - OOP 4_16.md
2026-04-16 11:47:56 +02:00

2.3 KiB

created, course, topic, related, type, status, tags
created course topic related type status tags
2026-04-16 08:01 lecture 🔴
university

📌 Summary

[!abstract]


📝 Content

Classes

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& p)
}