Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- // If the logic const is the goal, use mutable members to implement
- class BigArray
- {
- vector<int> v;
- //mutable int accessCounter; // first way.
- int accessCounter;
- public:
- int getItem(int index) const
- {
- //accessCounter++; // first way
- const_cast<BigArray*>(this)->accessCounter++; // Note: The casting is hacking way of coding, use it only when it had to.
- return v[index];
- }
- };
- int main()
- {
- // 1. The first way to change variable in const function is to declare the variable with the keyword mutable.
- // 2. The second is to cast the variable
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement