I can't seem to figure out why this code,
class test{
public:
int number;
test(int pass){
number = pass;
}
};
int main(){
test x(3);
test y(2);
test z[2]={x,y};
y.number = 1;
cout << "z[0].number: " << z[0].number << endl;
cout << "z[1].number: " << z[1].number << endl;
cout << "x.number: " << x.number << endl;
cout << "y.number: " << y.number << endl;
return 0;
}
Comes up with this output,
z[0].number: 3
z[1].number: 2
x.number: 3
y.number: 1
Instead of this one,
z[0].number: 3
z[1].number: 1
x.number: 3
y.number: 1
How can I make the second output possible? I've searched for this for three days, and still no luck :(
When you say:
test z[2] = {x, y};
z
holds two copy-constructed instances of test
. Since you didn't put in a copy constructor, it uses the default, which copies all data members. Thus, z
contains a copy of x
and a copy of y
. That's why changing y
doesn't change what's in z
. It's not like Java where everything is a reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With