Topic 46 of 83
OOP Intro
Overview
Object-Oriented Programming (OOP) revolves around bundling data (attributes) and behavior (methods) into individual 'objects'. The four main pillars are Encapsulation, Abstraction, Inheritance, and Polymorphism.
Syntax
cpp
// Procedural (C style):
// Data and functions are separate.
struct Car { int speed; };
void accelerate(Car& c) { c.speed += 10; }
// OOP (C++ style):
// Data and functions are grouped into an object.
class Car {
int speed;
public:
void accelerate() { speed += 10; }
};Common Pitfalls
- Forcing OOP onto tiny, simple scripts where functional or procedural programming would be cleaner (over-engineering).
Interview Tips
- Be able to clearly define the 4 pillars of OOP. Encapsulation: Hiding data. Abstraction: Showing only essential features. Inheritance: Reusing code. Polymorphism: One interface, many implementations.
Real-World Example
Comparing procedural thinking to OOP thinking.
example
cpp
/*
If you are building a banking app:
Procedural: You write functions like withdraw(account_id, amount)
and pass raw data structures around.
OOP: You create a BankAccount class.
An object of BankAccount knows its own balance,
and you simply call myAccount.withdraw(amount).
This models the real world much better.
*/