Using the object twice changes value

  • C/C++
  • Thread starter member 428835
  • Start date
  • Tags
In summary, there is an issue with calling the reverse function before the pointer points to it, leading to unexpected outputs. It is important to check the internal variables of the object being worked with to understand the behavior of the program.
  • #1

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.

#include <iostream>
class Solution {
    int r = 0;
    int new_num = 0;
    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
  • #2
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

Suggested for: Using the object twice changes value