Object Oriented Programming in C++Unit 19 min read
OOP Basics & C++: Paradigms, Paradigm Shift & Language Foundations
Unit 1 of Object Oriented Programming in C++ covers the core principles distinguishing OOP from procedural programming, C++'s role as a hybrid language, and foundational syntax (data types, I/O, control structures) that enable object-oriented design—with visual traces of program execution and real-world ties to Nepali
TAKEAWAYS
- OOP vs. POP: OOP bundles data + functions into objects (e.g.,
Personclass) while POP separates them (e.g., C’sstruct+ standalone functions); OOP’s encapsulation hides implementation details (e.g.,privatesalary inEmployee). - C++ as a hybrid: Supports both procedural (e.g.,
main()) and OOP (e.g.,class) code; itsstructcan have methods (unlike C), butclassdefaults toprivatedata. - Syntax pillars:
cout/cinfor I/O,if-else/switchfor control flow, and modularity via functions (e.g.,calculateTax()) prepare for classes. - Real-world modularity: Apps like Khalti use OOP to separate payment processing (class
Transaction) from user profiles (classCustomer), reducing bugs. - Non-linear complexity: OOP’s inheritance (e.g.,
Manager→Employee) creates exponential growth in code reuse, unlike POP’s linear functions. - Exam focus: Define encapsulation, abstraction, and modularity with code traces (show state changes) and comparison tables (OOP vs. POP).
1. Paradigm Shift: OOP vs. Procedural Programming (POP)
Key Differences
classDiagram
class POP {
+ Data + Functions Separate
+ Linear Code Flow
+ Example: C’s `struct` + `printf()`
}
class OOP {
+ Data + Functions Bundled (Objects)
+ State-Driven (Objects Have Identity)
+ Example: C++ `class` with `private`/`public`
}
POP -->|"Evolves into"| OOP : "Adds encapsulation"
OOP -->|"Uses"| POP : "For low-level tasks (e.g., I/O)"Why the shift?
POP (Procedural): Code is a sequence of steps acting on global data (e.g., C’s
main()modifyingglobal_array).// POP Example (C-style) struct Student { char name[50]; int roll; }; void printStudent(struct Student s) { printf("%s", s.name); }Problem: Data leakage (any function can modify
Student.roll).OOP: Data + functions are encapsulated in objects (e.g.,
Studentclass withprivaterollandpublicgetRoll()).class Student { private: // Hidden from outside int roll; public: void setRoll(int r) { roll = r; } // Controlled access };Advantage: Prevents invalid operations (e.g., setting
roll = -1).
Real-World Analogy: eSewa’s Transaction System
- POP Approach: A global
user_balancevariable. Any function (e.g.,transfer(),payBill()) can modify it → bug risk. - OOP Approach:
- Class
UserAccountencapsulatesbalanceand methodsdeposit(),withdraw(). - Class
Transactionhandles transfers by callingUserAccountmethods → safer, modular.
- Class
2. C++ Basics: The Hybrid Language
C++ merges POP and OOP. Key features:
- Backward compatibility: Runs C code (e.g.,
printf()). - OOP extensions:
class,struct,thispointer. - Standard Library:
iostream,vector,algorithm.
Syntax Foundations
#include <iostream> // Header for I/O
using namespace std; // Avoid writing std::cout
int main() {
// Variables
int age = 25; // Integer
double salary = 35000.5; // Floating-point
char grade = 'A'; // Character
bool isEmployed = true; // Boolean
// Input/Output
cout << "Enter your name: ";
string name;
cin >> name;
cout << "Hello, " << name << "! Your age is " << age << endl;
// Control Structures
if (age >= 18) {
cout << name << " is eligible to vote." << endl;
} else {
cout << name << " is not eligible." << endl;
}
// Loops
for (int i = 0; i < 5; i++) {
cout << "Iteration " << i << endl;
}
return 0; // Exit program
}
Trace Table for main() Execution:
| Step | age |
salary |
name (input) |
Output |
|---|---|---|---|---|
| 1 | 25 | 35000.5 | (uninitialized) | "Enter your name: " |
| 2 | 25 | 35000.5 | "Ramesh" | "Hello, Ramesh! Your age is 25" |
| 3 | 25 | 35000.5 | "Ramesh" | "Ramesh is eligible to vote." |
3. Modularity: Functions in C++
Functions enable reusability and abstraction (hiding complexity).
// Function to calculate tax (modularity)
double calculateTax(double income) {
const double TAX_RATE = 0.15; // 15% tax
return income * TAX_RATE;
}
int main() {
double income = 50000;
double tax = calculateTax(income);
cout << "Tax for Rs. " << income << " is Rs. " << tax << endl;
return 0;
}
Why modularity?
- Ncell Billing System: Uses functions like
calculateRoamingCharge()to avoid repeating logic across 10M users. - Daraz Order Processing:
processOrder()function handles inventory updates, payment checks, and shipping—one place to fix bugs.
4. Non-Linear Complexity in OOP
OOP’s inheritance and polymorphism create exponential code reuse, unlike POP’s linear functions.
Example: NTC’s Employee Hierarchy
- POP: Write separate functions for
Person,Employee,Manager→ 3x code duplication. - OOP: Inherit
EmployeefromPerson, thenManagerfromEmployee→ 1x base class, reusable methods.
Complexity Growth:
| Classes Added | POP Code Lines | OOP Code Lines |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 20 | 15 (+5 reuse) |
| 5 | 50 | 20 (+30 reuse) |
5. C++ Data Types and Memory
Primitive vs. User-Defined Types
Example: struct vs. class in C++
// struct (public by default)
struct Person {
string name;
int age;
void display() { cout << name << ", " << age << endl; }
};
// class (private by default)
class Person {
private: // Hidden
string name;
int age;
public:
void setName(string n) { name = n; }
void display() { cout << name << ", " << age << endl; }
};
Key Difference:
| Feature | struct |
class |
|---|---|---|
| Default Access | public |
private |
| Use Case | Simple data containers | Full OOP encapsulation |
6. Real-World Applications
1. Khalti’s Payment System
- OOP Idea: Encapsulation of
UserandTransactionclasses.Userclass hidesbalanceand exposestransfer().Transactionclass logs all transfers securely.
- POP Alternative: Global
user_balancesarray → hackable, no access control.
2. Pathao’s Ride Matching
- OOP Idea: Polymorphism for different vehicle types.
- Base class
VehiclewithcalculateFare(). - Derived classes
Bike,Car,AutooverridecalculateFare().
- Base class
- Code:
class Vehicle { public: virtual double calculateFare(double distance) = 0; // Pure virtual }; class Bike : public Vehicle { public: double calculateFare(double distance) override { return distance * 10; // Rs. 10/km } };
3. NEPSE Stock Trading
- OOP Idea: Inheritance for stock types.
- Base class
Stockwithbuy(),sell(). - Derived class
DerivativeStockaddsoptionExpiry().
- Base class
- Trace for
buy():sequenceDiagram participant User participant Stock participant Broker User->>Stock: buy(100 shares) Stock->>Broker: validateOrder() Broker-->>Stock: approved Stock->>User: confirm()
7. Exam Tip: How to Score Full Marks
Define with Examples:
- "Encapsulation is bundling data (e.g.,
private int salary) with methods (e.g.,public void promote()) to restrict direct access." - Visual: Draw a
class Employeewithprivatedata andpublicmethods.
- "Encapsulation is bundling data (e.g.,
Compare OOP vs. POP: Use a table like this:
Feature POP (C) OOP (C++) Data Access Global variables Encapsulated in classes Code Reuse Copy-paste functions Inheritance ( class A : B)Example printf()cout << obj.display()Trace Execution: For any program, show a step-by-step table of variable states (as above for
main()).Link to Real-World:
- "Like how Daraz uses
OrderandInventoryclasses to track shipments, OOP separates concerns." - Draw: A
class Orderwithprivateitemsandpublicship()method.
- "Like how Daraz uses
Avoid Common Mistakes:
- ❌ "C++ is purely OOP." → False: It supports POP too (e.g.,
main()). - ❌ "All member functions are
public." → False: Default isprivateinclass.
- ❌ "C++ is purely OOP." → False: It supports POP too (e.g.,
Final Checklist for Exams:
- Define encapsulation, abstraction, modularity with code snippets.
- Compare
structvs.classin a table. - Trace variable states for a given program.
- Relate to Nepali apps (e.g., Khalti’s
Userclass).
Based on the PU BE Computer (PU) syllabus for Object Oriented Programming in C++, unit 1.
Discussion
Loading…