Classes & Object-Oriented Programming (OOP) in C++
๐ก Intermediate
๐ Definition
Object-Oriented Programming (OOP) is a design paradigm centered around Classes (user-defined blueprints) and Objects (real-world instances of classes holding state and behavior). The four core pillars of OOP are:
- Encapsulation: Bundling member variables and methods inside a class and restricting direct access via access specifiers (
private,public,protected). - Abstraction: Exposing only essential interface methods while hiding complex internal implementation logic.
- Inheritance: Creating new derived classes from existing base classes.
- Polymorphism: Overriding base class functions at runtime using virtual methods.
๐ฎ๐ณ Hindi Explanation
- Class: Ek khali blueprint / format hota hai (jaise Bank Account ka form).
- Object: Us blueprint se bana real instance (jaise Rahul ka Bank Account).
- Encapsulation: Class ke sensitive variables (jaise
balance) koprivaterakhna taaki koi bahar se use directly change na kar sake. Access sirfpublicmethods (deposit(),withdraw()) ke zariye milta hai.
๐ฉ Marathi Explanation
- Class: Ek blueprint aahe (udaharanarth Car cha design).
- Object: Tyapasun banavleli pratyaksh vastu (udaharanarth Tesla Car).
- Encapsulation: Data safe thevnyasathi variables
privatethevane aani tyaana badalnyasathipublicfunctions vaparne.
๐ Access Specifiers in C++
| Access Specifier | Accessible Inside Class? | Accessible In Derived Class? | Accessible Outside Class? |
|---|---|---|---|
private |
โ Yes | โ No | โ No |
protected |
โ Yes | โ Yes | โ No |
public |
โ Yes | โ Yes | โ Yes |
๐ก Practical Example
#include <iostream>
#include <string>
// Class Definition (Blueprint)
class BankAccount {
private:
std::string accountNumber;
std::string accountHolder;
double balance; // Encapsulated private data!
public:
// Constructor (Initializes Object State)
BankAccount(std::string accNum, std::string holder, double initialBalance) {
accountNumber = accNum;
accountHolder = holder;
balance = (initialBalance >= 0.0) ? initialBalance : 0.0;
}
// Public Method: Deposit Money
void deposit(double amount) {
if (amount > 0.0) {
balance += amount;
std::cout << "[SUCCESS] Deposited $" << amount << ". New Balance: $" << balance << std::endl;
} else {
std::cout << "[ERROR] Deposit amount must be positive!" << std::endl;
}
}
// Public Method: Withdraw Money with Validation
void withdraw(double amount) {
if (amount > 0.0 && amount <= balance) {
balance -= amount;
std::cout << "[SUCCESS] Withdrew $" << amount << ". Remaining Balance: $" << balance << std::endl;
} else {
std::cout << "[ERROR] Insufficient funds or invalid amount!" << std::endl;
}
}
// Getter Method for Reading Encapsulated Balance
double getBalance() const {
return balance;
}
void displayDetails() const {
std::cout << "Acc Num: " << accountNumber << " | Holder: " << accountHolder << " | Balance: $" << balance << std::endl;
}
};
int main() {
std::cout << "--- CREATING BANK ACCOUNT OBJECTS ---" << std::endl;
// Instantiating BankAccount Object
BankAccount acc1("ACC-1001", "Rahul Sharma", 1000.00);
acc1.displayDetails();
acc1.deposit(500.00);
acc1.withdraw(200.00);
acc1.withdraw(2000.00); // Triggers insufficient funds guard!
// Direct access to private member is blocked by compiler!
// acc1.balance = 500000.00; // COMPILATION ERROR!
return 0;
}
๐ Code Breakdown
class BankAccount: Defines a custom data structure holding variables and methods.private:: Protectsbalancefrom being directly altered frommain().deposit()andwithdraw(): Encapsulate valid business rules and data safety guards.double getBalance() const: Read-only public method for querying current balance safely.
๐ Output
--- CREATING BANK ACCOUNT OBJECTS ---
Acc Num: ACC-1001 | Holder: Rahul Sharma | Balance: $1000
[SUCCESS] Deposited $500. New Balance: $1500
[SUCCESS] Withdrew $200. Remaining Balance: $1300
[ERROR] Insufficient funds or invalid amount!
โ ๏ธ Common Mistakes
- Forgetting Semicolon After Class Definition: Writing
class Car { ... }without the ending semicolon;causes a confusing compilation error! Always end class definitions with};. - Default Access Specifier in
classvsstruct:- In a
class, members areprivateby default. - In a
struct, members arepublicby default.
- In a
๐ก๏ธ Best Practices
- Always keep member variables
privateand provide getters/setters as needed (Encapsulation Principle). - Mark getter methods
constif they do not alter any object variables (double getBalance() const).
๐งช Try It Yourself
- Create a
Studentclass with private attributesname,rollNumber, andmarks. Add a methodhasPassed()that returnstrueifmarks >= 40.
๐ฏ Mini Challenge
Design a Rectangle class with private members length and width. Include methods setDimensions(l, w), calculateArea(), and calculatePerimeter().
๐ Related Topics
๐งญ Navigation
| โ C++ Home | โ Previous: Arrays & Vectors | Next: Constructors & Destructors โ |