189. Shadowing Resolution

Back To All Submissions
Previous Submission
Next Submission
#include <iostream>

/**
 * Timer Class
 * Manages a time period and demonstrates how to resolve
 * variable name conflicts using the 'this' pointer.
 */
class Timer {
private:
    int period = 0; // Member variable

public:
    /**
     * Sets the timer period.
     * @param period: The new period value (shadows the member variable).
     */
    void setPeriod(int period) {
        // 'this->period' refers to the private member variable.
        // 'period' refers to the parameter passed into the function.
        this->period = period;
    }

    /**
     * Logs the current period to the standard output.
     */
    void log() {
        std::cout << "Timer Period: " << period << " ms" << std::endl;
    }
};

int main() {
    Timer t;
    int N;

    // Read the number of iterations
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        int p;
        if (std::cin >> p) {
            t.setPeriod(p); // Update the timer
            t.log();        // Print the result
        }
    }
    
    return 0;
}

Solving Approach

 

 

 

 

 

 

Was this helpful?
Upvote
Downvote