PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] Why is object member value changing between 2 getter calls

 July 04, 2022     c++, constructor, pass-by-reference, pass-by-value     No comments   

Issue

I am getting unexpected value in second getter call which looks wrong to me, any specific reason for this happening?

#include<iostream>

using namespace std;

class Test {

public:
    int &t;
    Test (int x):t(x) { }
    int getT() { return t; }
};

int main() {
    int x = 20;
    Test t1(x);
    cout << t1.getT() << " ";
    cout << t1.getT() << endl;

        
    return 0;
}

Solution

The problem here is that your code results in undefined behavior.

The constructor of Test does not take a reference to an int but a copy, and due to int x only being a temporary copy which is not guaranteed to live until your second function call you will end up with undefined behavior.

You would have to change your constructor to the following to make the code work properly:

Test(int& x) : t(x) {}

Now the reference you're working with in Test will be the same x as defined in main



Answered By - Noah
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing