Using the object twice changes value

  • C/C++
  • Thread starter member 428835
  • Start date
  • Tags
    Value
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.

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
  • #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

FAQ: Using the object twice changes value

Why does using an object twice change its value?

Using an object twice does not inherently change its value. It is possible that the object has a method or attribute that modifies its value when called multiple times.

Can using an object twice cause unintended side effects?

Yes, using an object multiple times can result in unintended side effects if the object contains methods or attributes that have side effects.

How can I prevent an object from changing value when used twice?

You can prevent an object from changing value by carefully designing and implementing its methods and attributes to avoid unintended side effects.

Is using an object twice considered bad practice?

Using an object twice is not necessarily considered bad practice, but it is important to be aware of any potential side effects and design the object accordingly.

Are there any benefits to using an object twice?

Using an object twice can be beneficial if the object is designed to efficiently handle multiple uses and does not cause any unintended side effects.

Similar threads

Replies
22
Views
3K
Replies
1
Views
1K
Replies
10
Views
2K
Replies
13
Views
2K
Replies
36
Views
4K
Replies
118
Views
8K
Replies
8
Views
2K
Back
Top