Using the object twice changes value

  • Context: C/C++ 
  • Thread starter Thread starter member 428835
  • Start date Start date
  • Tags Tags
    Value
Click For Summary
SUMMARY

The discussion centers on the behavior of the `reverse` method in the `Solution` class, specifically how the internal state of the object affects output. When the `reverse` method is called the first time, it initializes `new_num` to zero, resulting in an output of 1 for the input 10. However, upon the second call via a pointer, the internal state retains the value of `new_num`, leading to an output of 101. This behavior is due to the persistent state of class member variables across method calls.

PREREQUISITES
  • Understanding of C++ class structures and member variables
  • Familiarity with pointers and object references in C++
  • Basic knowledge of control flow in C++ (loops and conditionals)
  • Experience with debugging techniques, such as using print statements
NEXT STEPS
  • Explore C++ class member variable scope and lifetime
  • Learn about object-oriented programming principles in C++
  • Investigate the use of `const` and `static` keywords in C++ classes
  • Practice debugging C++ code using breakpoints and watch variables
USEFUL FOR

C++ developers, software engineers, and students learning object-oriented programming concepts who want to understand the implications of object state and method calls in class instances.

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   Reactions: member 428835

Similar threads

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