Previous chapter: Chapter 8: References, Call by Value vs. Call by Reference
C++ is a multi-paradigm language, but its strength lies in Object-Oriented Programming (OOP). OOP provides a powerful structure for designing complex programs by modeling real-world entities as software objects.
1. Key Concepts of OOP
The OOP paradigm is built on four pillars:
Encapsulation: Binding data (variables) and the methods (functions) that operate on that data into a single unit (a class). It also involves restricting direct access to some components.
Abstraction: Hiding complex implementation details and showing only the essential information to the user.
Inheritance: Allowing one class to acquire the properties and behavior of another class, promoting code reuse.
Polymorphism: The ability of an object or function to take on many forms (e.g., a function behaving differently depending on the objects it is called upon).
2. Classes and Objects
Classes: The Blueprint
A class is a user-defined blueprint or template for creating objects. It defines the structure (data members) and the behavior (member functions/methods) that all objects of that class will possess.
class Car {
private:
std::string color; // Data member
int speed; // Data member
public:
// Member function (method)
void accelerate(int value) {
speed += value;
}
void display_speed() {
std::cout << "Current speed: " << speed << " km/h" << std::endl;
}
};
Objects: The Instance
An object is an instance of a class. When you create an object, memory is allocated according to the class blueprint, and you can access its public features.
int main() {
Car my_car; // Declares an object (instance) of the Car class
// Accessing public members via the dot operator (.)
my_car.accelerate(50);
my_car.display_speed(); // Output: Current speed: 50 km/h
// Car another_car; // You can create multiple, independent objects
return 0;
}
3. Access Modifiers
Access modifiers control the visibility and accessibility of class members. This is the mechanism C++ uses to enforce encapsulation.
public: Members declared as public are accessible from anywhere outside the class. Member functions like accelerate() and display_speed() are usually public interfaces.
private: Members declared as private are only accessible from within the same class. Data members (like color and speed) are typically private to protect their integrity.
protected: Used in inheritance (Chapter 11) to allow access only to the class itself and its derived subclasses.
4. Structs vs. Classes in C++
C++ retains the struct keyword from C. While syntactically similar, the key difference lies in the default access modifier:
In modern C++, classes are generally used for OOP concepts where data hiding (private access) is important, while structs are often reserved for simple data-only containers (often referred to as Plain Old Data or POD structures).