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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
class 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 2 3 4 5
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 2 3 4
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#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.