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 objectExample: 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,
thisensures the current transaction object (not a temporary copy) updates its status. For example, inTransaction::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 totalBooksin aBookclass). - 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 sharedExample: 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 totalConnectionsin aNetworkDeviceclass tracks all active connections across all devices, updated viathis->totalConnections++in each device’sconnect()method. - NEPSE stock ticker: The
static double totalMarketValuein aStockclass accumulates all shares’ values, accessed viaStock::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:
- Implicit conversion: Automatic (e.g.,
Dollar d = rupeeObj;). - Explicit conversion: Requires
explicitkeyword (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
RupeetoDollarfor international transactions using implicit conversion inPayment::process(). - Pathao’s fare calculator: Converts
Distance(in km) toTime(in minutes) for estimated arrival times viaoperator 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
thispointer:- 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).
- Always use
Static members:
- Initialize outside the class (e.g.,
int Book::totalBooks = 0;). - Access via
ClassName::member(no object needed).
- Initialize outside the class (e.g.,
Conversions:
- Prefer
explicitfor conversions to avoid unintended implicit calls. - Conversion operators must be member functions of the source class.
- Prefer
Common pitfalls:
- Forgetting to initialize static members (compiler error).
- Overloading
=or()for conversions (not allowed). - Using
thisin static functions (invalid—static functions have nothis).
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…