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
Thread 'Star maps using Blender'
Blender just recently dropped a new version, 4.5(with 5.0 on the horizon), and within it was a new feature for which I immediately thought of a use for. The new feature was a .csv importer for Geometry nodes. Geometry nodes are a method of modelling that uses a node tree to create 3D models which offers more flexibility than straight modeling does. The .csv importer node allows you to bring in a .csv file and use the data in it to control aspects of your model. So for example, if you...
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...

Similar threads

Back
Top