Why doesn't the variable change as expected?
Dec 10, 2019 at 9:27am UTC  
Ok so I'll admit i haven't been programming for a very while and I was trying to familiarize myself with how things work.
So here goes.
1class  sample
{
    public :
    string x;
    sample(string y)
    {
      x=y;  
    };
    sample operator += (sample y)
    {
        return  sample(this ->x+y.x);
    }
    void  print()
    {
        cout<<x<<"\n" ;
    }
};
int  main()
{
    sample x("Hello " ),y("There" );
    x+=y;
    x.print();//why isn't the x variable modified? 
}
I know that it can be done ike this
1    sample const  operator += (const  sample &y)
    {
        this ->x=this ->x+y.x;
        return  *this ;
    }
But I still want to know why doesn't my first variant work.
I'm pretty sure it has something to do with values and references but i couldn't find an answer specific to this example.
Thanks for answering :).
Last edited on Dec 10, 2019 at 9:45am UTC  
 
Dec 10, 2019 at 10:09am UTC  
 x+=y;
This code could be seen as:
x.+=(y);
That is, calling the 'class function' 
+= on the object 
x, with the parameter 
y.
Let's look at what that function does:
1 sample operator += (sample y)
    {
        return  sample(this ->x+y.x);
    }
It creates a completely new object of type sample, with the constructor 
sample(string y). A completely new one. Does it alter the existing class object (i.e. the 
x in  
x+=y;) at all? No. 
Nothing to do with passing by value or reference. You're just not making any changes at all to the object.
 
Last edited on Dec 10, 2019 at 10:10am UTC  
 
Dec 10, 2019 at 10:13am UTC  
I think this is what you're trying to do:
 1#include <iostream> 
#include <string> 
using  namespace  std;
class  sample
{
    public :
    string x;
    sample(string y)
    {
      x=y;  
    }
    void  operator += (sample y)
    { 
        x = (this ->x + y.x);
    }
    void  print()
    {
        cout<<x<<"\n" ;
    }
};
int  main()
{
    sample x("Hello " ),y("There" );
    x+=y;
    x.print();//why isn't the x variable modified? 
}
 
Dec 10, 2019 at 1:28pm UTC  
operator+= generally should return a reference to the object changed.
 
Topic archived. No new replies allowed.