← C++ from Scratch
Lesson 34 of 62 · 5 XP
OOP: objects instead of scattered data
Theory
Machine translation, not yet reviewed by a native speaker.
Object-oriented programming is a way of keeping data and the actions on it together.
Instead of separate variables heroHp, heroName and functions heroAttack(...), there's one class Hero
that has fields (data) and methods (actions).
The four ideas of OOP:
- Encapsulation — an object guards its own data: from the outside you can't make the health negative,
you can only call
takeDamage(), which checks the limits. - Inheritance —
MageandWarriorareHeros: they get its fields and methods and add their own. - Polymorphism — one call
hero->attack()does different things for a mage and a warrior. - Abstraction — from the outside you see what an object can do, not how it's built inside.
A class is a blueprint, and an object is a specific thing made from the blueprint:
class Hero { … }; // the blueprint
Hero kai; // an object
Hero alex; // another object, with its own data
OOP isn't the only way to write programs, and not always the best one. In games, for example, the ECS approach (entities, components, systems) is popular. But classes are the foundation of C++: without them you can't understand the STL or game engines.