In previous chapters we defined an object in C++ as, “a piece of memory that can be used to store values”. An object with a name is called a variable. Our C++ programs have consisted of sequential list of lists of instructions to the computer that define data (via objects) and operations performed on that data (via functions containing statements and expressions).
Up to now, we have been doing a type of programming called procedural programming. In procedural programming, the focus on creating “procedures” (which in C++ is called functions) that implement our program logic. We pass data objects to these functions, those functions perform operations on the data, and then potentially return a result to the caller.
In procedural programming, the functions and the data those functions operate on are separate entities. The programmer is responsible for combining the functions and the data together to produce the desired result. This leads to code that looks like this:
eat(you, apple);
Now, take a look around you – everywhere you look are objects: books, buildings and food and even you. Such objects have two major components to them:
- Some number of associated properties (e.g., weight, color, size, shape, etc.).
- Some number of behaviors that they can exhibit (e.g. being opened, making something else hot, etc.). These properties and behaviors are inseparable.
In programming, properties are represented by objects, and behaviors are represented by functions. And thus, procedural programming represents reality fairly poorly, as it separates properties (objects) and behaviors (functions).
What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a programming paradigm that seeks to bridge the gap between data and the functions that operate on that data. OOP combines data and behavior into a single entity known as an object. In OOP, objects are instances of classes, which define both the properties (attributes) and behaviors (methods) of an object.
OOP allows us to represent real-world entities more intuitively by integrating their properties and behaviors into cohesive units. Instead of separating functions and data, we bundle them together in a way that models reality more naturally. For example, an object representing a car might have properties like speed and color, and methods like accelerate or brake:
class Car {
public:
int speed;
string color;
void accelerate() {
speed += 10;
}
void brake() {
speed = 0;
}
};
Here, the Car
class encapsulates both the properties (speed
, color
) and the behaviors (accelerate()
, brake()
) of a car, combining them into a single entity. This approach reflects the real-world notion that objects have both attributes and actions, which are inherently linked.