C/C++ Using the object twice changes value

  • Thread starter Thread starter member 428835
  • Start date Start date
  • Tags Tags
    Value
AI Thread 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
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Back
Top