CSC166 Object Oriented Programming

Object Oriented ProgrammingUnit 96 min read

Advanced OOP: This Pointer, Static Members & User-Defined Conversions

Unit 9 of Object Oriented Programming explores three advanced C++ concepts: the this pointer for object self-reference, static members for shared class data, and user-defined type conversions for flexible object interactions—with real-world applications in financial systems, inventory management, and unit conversions.

Core Concepts

1. The this Pointer

Definition: A hidden pointer automatically passed to member functions, pointing to the current object instance.

How it works:

  • Used when a member function needs to refer to the object itself (e.g., to disambiguate between instance variables and parameters).
  • Cannot be modified (it’s a constant pointer).
  • Useful in constructors, operator overloading, and function chaining.

Visual: this pointer in action

classDiagram
    class Person {
        +String name
        +setName(name: String) void
    }
    Person --> "this" Person : points to current object

Example: Disambiguation

class Counter {
    int count;
public:
    void increment(int value) {
        count += value;  // count is instance variable
        this->count += 1; // explicit this-> for clarity
    }
};

Real-world tie-in:

  • eSewa’s transaction system: When processing a payment, this ensures the current transaction object (not a temporary copy) updates its status. For example, in Transaction::process(), this->status = "completed" guarantees the correct object is modified.

2. Static Members

Definition: Class members shared by all instances of the class (not tied to any object).

Key features:

  • Static data members: Shared across all objects (e.g., static int totalBooks in a Book class).
  • Static member functions: Can be called without an object (e.g., Book::getTotalBooks()).
  • Memory: Stored in the static storage area (not on the heap/stack).

Visual: Static vs. instance members

classDiagram
    class Book {
        -String title
        +static int totalBooks
        +Book() { totalBooks++; }
    }
    Book "1" --> "1..*" Book : totalBooks shared

Example: Inventory tracking

class Book {
    static int totalBooks;
    string title;
public:
    Book(string t) { title = t; totalBooks++; }
    static int getTotal() { return totalBooks; }
};
int Book::totalBooks = 0; // Initialize static member

Real-world tie-in:

  • NTC’s network traffic counters: A static int totalConnections in a NetworkDevice class tracks all active connections across all devices, updated via this->totalConnections++ in each device’s connect() method.
  • NEPSE stock ticker: The static double totalMarketValue in a Stock class accumulates all shares’ values, accessed via Stock::getTotalMarketValue() without instantiating any object.

Exam tip: Always initialize static members outside the class (e.g., int Book::totalBooks = 0;).


3. User-Defined Conversions

Definition: Overloading the operator to convert between user-defined types (e.g., Rupee to Dollar).

Types:

  1. Implicit conversion: Automatic (e.g., Dollar d = rupeeObj;).
  2. Explicit conversion: Requires explicit keyword (e.g., Dollar d = static_cast<Dollar>(rupeeObj);).

Visual: Conversion flow

flowchart TD
    A["Rupee obj"] -->|"implicit"| B["Dollar obj"]
    A -->|"explicit"| C["Dollar obj"]

Example: Currency conversion

class Rupee {
    int amount;
public:
    operator Dollar() const { return Dollar(amount / 133); }
};

class Dollar {
    int amount;
public:
    Dollar(int a) : amount(a) {}
};

Real-world tie-in:

  • Khalti’s payment gateway: Converts Rupee to Dollar for international transactions using implicit conversion in Payment::process().
  • Pathao’s fare calculator: Converts Distance (in km) to Time (in minutes) for estimated arrival times via operator Time().

Worked example: Bank loan interest

class Loan {
    double principal;
public:
    operator double() const { return principal * 1.05; } // 5% interest
};

int main() {
    Loan homeLoan(1000000);
    double totalDue = homeLoan; // Implicit conversion to double
    cout << "Total due: " << totalDue; // Output: 1050000
}

Trace:

Step principal totalDue (after conversion)
Initial 1,000,000 N/A
Conversion 1,000,000 1,050,000 (1,000,000 * 1.05)

Comparison Table: Key Differences

Feature this Pointer Static Members User-Defined Conversion
Scope Instance-specific Class-wide Type-specific
Memory Location Stack/Heap Static storage N/A
Syntax this->member static keyword operator type()
Use Case Disambiguation Shared data Type flexibility
Example this->count++ static int count operator Dollar()

Exam Tips

  1. this pointer:

    • Always use this-> when a parameter name shadows a member variable (e.g., setName(string name)).
    • Cannot be reassigned (e.g., this = new Object() is invalid).
  2. Static members:

    • Initialize outside the class (e.g., int Book::totalBooks = 0;).
    • Access via ClassName::member (no object needed).
  3. Conversions:

    • Prefer explicit for conversions to avoid unintended implicit calls.
    • Conversion operators must be member functions of the source class.
  4. Common pitfalls:

    • Forgetting to initialize static members (compiler error).
    • Overloading = or () for conversions (not allowed).
    • Using this in static functions (invalid—static functions have no this).

Visual recap:

mindmap
  root((Advanced OOP))
    thisPointer
      definition
      usage["this->member"]
      example["Counter::increment()"]
    staticMembers
      data["shared across objects"]
      function["callable without object"]
      example["Book::totalBooks"]
    conversions
      implicit["automatic"]
      explicit["requires cast"]
      example["Rupee → Dollar"]

Based on the TU BSc CSIT syllabus for Object Oriented Programming (CSC166), unit 9.

Discussion

Loading…