C/C++ Using the object twice changes value

  • Thread starter Thread starter member 428835
  • Start date Start date
  • Tags Tags
    Value
Click For Summary
The issue arises from the use of the same object, `ob1`, for two calls to the `reverse` method, which modifies the internal state of the object. The first call resets `new_num` to zero, but the second call uses the updated state, leading to different outputs. When `reverse` is called the second time via the pointer, it reflects the changes made during the first call. Adding a print statement at the start of the `reverse` method can help verify the state of `new_num`. Understanding object state management is crucial in this scenario.
member 428835
Can't figure out the code below why the second output in main outputs 101 instead of 1. Something about calling ob1.reverse(s) before the pointer points to reverse(s), but I'm confused. Any help is much appreciated.

C++:
#include <iostream>
class Solution {
private:
    int r = 0;
    int new_num = 0;
public:
    int reverse(int s_) {
        while(s_ > 0) {
            r = s_ % 10;
            new_num = new_num*10 + r;
            s_ = (s_ - r)/10;
        }
        return new_num;
    }
};
int main()
{
    int s = 10;
    Solution ob1;
    auto sol = ob1.reverse(s);
    std::cout << sol <<"\n";
   
   Solution* ptr = &ob1;
    int a = ptr->reverse(s);
    std::cout << a <<"\n";
}
 
Technology news on Phys.org
youre working with obj1 directly and via a pointer. The first time using obj1 it’s internal variables are set to zero.

The second time you work with obj1 via a pointer the variables are set to what they were from the first time.

You can check this by adding a print statement to the start of the reverse method to see whether the internal variable new_num is zero or not.
 
  • Like
Likes member 428835

Similar threads

  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 13 ·
Replies
13
Views
3K
  • · Replies 36 ·
Replies
36
Views
5K
  • · Replies 118 ·
3
Replies
118
Views
9K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
12
Views
3K
  • · Replies 4 ·
Replies
4
Views
1K