From the course: Object-Oriented Programming with C++

Unlock this course with a free trial

Join today to access over 24,800 courses taught by industry experts.

Challenging const correctness

Challenging const correctness - C++ Tutorial

From the course: Object-Oriented Programming with C++

Challenging const correctness

- [Instructor] Let's assume we want to track how many times a review has been read. We'll need a new member variable to store the excess count. Let's declare it in the private section of our class. It should be an unsigned integer, and I'll call it accessCount and initialize it right away to zero. Okay, now where should we update it? The obvious place to increment this counter is in our displayDetails method. Let's switch to our implementation and make the necessary changes. I'll increment it here. We'll also include the accessCount in the log message. So I'll add a new line here and add the accessCount value saying Read and the accessCount number of times. Okay, let's run it. We have a problem. As you may recall, we marked the displayDetails method const because it shouldn't change the object's internal state. Now that has changed, as we want to update our access counter. That's why our program wouldn't compile. One way to address this issue is to remove the const from the…

Contents