Elective Object Oriented Programming in C++

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., Person class) while POP separates them (e.g., C’s struct + standalone functions); OOP’s encapsulation hides implementation details (e.g., private salary in Employee).
  • C++ as a hybrid: Supports both procedural (e.g., main()) and OOP (e.g., class) code; its struct can have methods (unlike C), but class defaults to private data.
  • Syntax pillars: cout/cin for I/O, if-else/switch for 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 (class Customer), 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() modifying global_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., Student class with private roll and public getRoll()).

    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_balance variable. Any function (e.g., transfer(), payBill()) can modify it → bug risk.
  • OOP Approach:
    • Class UserAccount encapsulates balance and methods deposit(), withdraw().
    • Class Transaction handles transfers by calling UserAccount methods → safer, modular.

2. C++ Basics: The Hybrid Language

C++ merges POP and OOP. Key features:

  1. Backward compatibility: Runs C code (e.g., printf()).
  2. OOP extensions: class, struct, this pointer.
  3. Standard Library: iostream, vector, algorithm.
ExtendsAddsRetainsCC++OOP FeaturesPOP Features
C++ as a hybrid: Combines C’s procedural features with OOP additions

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.

PersonEmployeeStudentManagerCEO
Inheritance hierarchy: Base class (Person) → Derived classes (Employee, Student, etc.)

Example: NTC’s Employee Hierarchy

  • POP: Write separate functions for Person, Employee, Manager → 3x code duplication.
  • OOP: Inherit Employee from Person, then Manager from Employee → 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

Primitive Types (int, float, char, bool) (40%)User-Defined Types (class, struct, enum) (60%)
C++ data type distribution (simplified for clarity)

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 User and Transaction classes.
    • User class hides balance and exposes transfer().
    • Transaction class logs all transfers securely.
  • POP Alternative: Global user_balances array → hackable, no access control.

2. Pathao’s Ride Matching

  • OOP Idea: Polymorphism for different vehicle types.
    • Base class Vehicle with calculateFare().
    • Derived classes Bike, Car, Auto override calculateFare().
  • 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 Stock with buy(), sell().
    • Derived class DerivativeStock adds optionExpiry().
  • 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

  1. 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 Employee with private data and public methods.
  2. 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()
  3. Trace Execution: For any program, show a step-by-step table of variable states (as above for main()).

  4. Link to Real-World:

    • "Like how Daraz uses Order and Inventory classes to track shipments, OOP separates concerns."
    • Draw: A class Order with private items and public ship() method.
  5. Avoid Common Mistakes:

    • ❌ "C++ is purely OOP." → False: It supports POP too (e.g., main()).
    • ❌ "All member functions are public." → False: Default is private in class.

Final Checklist for Exams:

  • Define encapsulation, abstraction, modularity with code snippets.
  • Compare struct vs. class in a table.
  • Trace variable states for a given program.
  • Relate to Nepali apps (e.g., Khalti’s User class).

Based on the PU BE Computer (PU) syllabus for Object Oriented Programming in C++, unit 1.

Discussion

Loading…