Object Oriented Programming
Object-Oriented Programming (OOP) in C++ shifts the focus from the actions your program performs (procedural programming) to the data and objects that drive those actions. Instead of primarily thinking about functions—like “verbs”—you’ll also think about nouns (objects) that have both attributes (data) and functionality (methods).
What Is It?
Section titled “What Is It?”-
Procedural Programming: Focuses on actions (functions) and the order in which they’re performed.
-
Object-Oriented Programming: Focuses on objects (the “nouns”), their attributes (data), and their behavior (methods or functions).
Why Use It?
Section titled “Why Use It?”-
Data Encapsulation: Grouping data and the methods that operate on that data together into classes makes your code more organized and manageable.
-
Reusability: Classes can be reused in different parts of a program or in different projects, reducing duplication and saving time.
-
Maintainability: Keeping related data and functions together helps prevent errors and makes updating or extending functionality more straightforward.
Example
Section titled “Example”To illustrate the principles of Object-Oriented Programming, imagine
creating a Character class in a video game. This class represents a
broad category of characters that share common attributes and behaviors.
For example, a character might have:
Data (Attributes)
Section titled “Data (Attributes)”-
Inventory: A collection of items the character carries.
-
Health: The current health points of the character.
-
Attack Power: How much damage the character can deal.
-
Defense: How well the character can withstand attacks.
-
Speed: How quickly the character can move or act.
Behavior (Methods)
Section titled “Behavior (Methods)”-
Add Item to Inventory: Allows the character to pick up items or equipment.
-
Attack: Performs an attack on an enemy, affecting their health.
Specific Types
Section titled “Specific Types”From this Character base class, you can create more specific types of characters, such as a Mage or a Warrior, each with specialized data (like mana for a Mage or rage for a Warrior) and unique behaviors (like casting spells vs. using melee attacks).
