Search code examples
c++returnthis-pointer

*this (Return reference to the calling object) does not return changed object's value in that function


Suppose there are two object : num1 , num2 each store integer number of 5 .

I want to add both object's value using non member function so result is : 10 .

But THE OUTPUT show value : 5 .

Is there any error in class member function or *this pointer ?

main.cpp

#include<iostream>
#include"Person.h"  
using namespace std ;

int main(){
    Person num1 ;
    Person num2 ;

    num1.InValueCapture(5) ;
    num2.InValueCapture(5) ;

    add(num1,num2);   //non class member function  : num1+num2 expecting result : 10           
    
    cout << "THE OUTPUT : " << num1.GetValueCapture() << endl; //but now we get 5 
    return 0 ;
}

Person.h

#ifndef PERSON.H
#define PERSON.H

struct Person{
private:
    int value_capture ;
public:

    int InValueCapture(int value){
        value_capture = value ;
    }

    int GetValueCapture() const {
        return value_capture ;
    }

    //adding two data
    Person& combine(const Person &Rdata)
    {
        value_capture += Rdata.value_capture ;
        std::cout << "value capture : " << value_capture <<std::endl; // use to check value inside DataSum.value_capture

        return *this ;
    }
};



Person add(const Person &Ldata , const Person &Rdata)       //nonmember function 
{
    Person DataSum = Ldata;
    DataSum.combine(Rdata);  // add Rdata to Ldata , call class function combine
    return DataSum ;        //
}

#endif

Thank you for your guidance , appreciate your help .


Solution

  • Comments are liars:

    DataSum.combine(Rdata);  // add Rdata to Ldata , call class function combine
    

    This does not "add Rdata to Ldata". You are calling a method of DataSum which is a copy of LData. Modifiying the copy has no effect on the original LData. Don't make a copy:

    void add(Person &Ldata , const Person &Rdata)       //nonmember function 
    {
        Ldata.combine(Rdata);  // add Rdata to Ldata , call class function combine
    }
    

    Actually I am not 100% sure what the function is supposed to do. If you want to modify the first parameter you cannot pass it as const reference. If you want to not modify it passing const reference is fine, then you can return the result, but thats already what your function does, just that you ignore the returned value. I removed the return to make it more clear that the function modifies its first parameter. Though, now the caller can as well call combine directly.