Object-Oriented Programming (OOP) is a programming approach that organizes code into objects, combining data and functions that operate on that data.
C++ is a multi-paradigm language, but it strongly supports OOP features.
Why Use OOP?
- To model real-world entities using code
- Helps write modular, reusable, and maintainable programs
- Makes large-scale software easier to manage
Four Main Pillars of OOP
| Concept | Description |
|---|
| Encapsulation | Bundling data and functions into a single unit (class) |
| Abstraction | Hiding internal details and showing only necessary info |
| Inheritance | Reusing code by deriving new classes from existing ones |
| Polymorphism | Ability of one function to behave differently based on context |
Key OOP Terms in C++
| Term | Meaning |
|---|
| Class | Blueprint or template for creating objects |
| Object | Instance of a class |
| Method | Function defined inside a class |
| Data Member | Variable inside a class |
Example: Simple Class and Object
#include <iostream>
using namespace std;
class Car {
public:
string brand;
void start() {
cout << brand << " is starting...\n";
}
};
int main() {
Car c1;
c1.brand = "Toyota";
c1.start();
return 0;
}
Access Specifiers
| Specifier | Access Level |
|---|
public | Accessible from anywhere |
private | Accessible only within the class |
protected | Accessible in the class and derived classes |
OOP in Action
| Feature | Example Use Case |
|---|
| Encapsulation | Hiding data in classes |
| Inheritance | Creating a Bike class from a Vehicle class |
| Polymorphism | Overloading functions or overriding methods |
| Abstraction | Using abstract classes/interfaces |