148. Shadowing Resolution

#include <iostream>

class Timer {
private:
    int period = 0;

public:
    void setPeriod(int period) {
        // 'this->period' refers to the member variable.
        // 'period' refers to the local argument.
        this->period = period;
    }

    void log() {
        std::cout << "Timer Period: " << period << " ms" << std::endl;
    }
};

int main() {
    Timer t;
    int N;
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        int p;
        std::cin >> p;
        t.setPeriod(p);
        t.log();
    }
    return 0;
}

Explanation & Logic Summary:

  • Shadowing: When a local variable (argument) has the same name as a member variable, the compiler prioritizes the local one.
  • The Fix: this is a pointer to the object itself. this->period explicitly tells the compiler "go to the object's memory and find the variable named period," bypassing the local argument scope.
  • Why do this? It avoids awkward naming conventions like void setPeriod(int p) or void setPeriod(int _period). The code is self-documenting: you are setting the period with a period.

Firmware Relevance & Real-World Context:

  • Driver APIs: In large projects, keeping variable names consistent (e.g., always using frequency instead of freq, f, frq) reduces cognitive load. Using this-> allows you to maintain that consistency in both the public API and the internal storage.

 

 

 

 

Loading...

Input

2 100 500

Expected Output

Timer Period: 100 ms Timer Period: 500 ms