C++ Class returning old values? -
i can't seem figure out why 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 output,
z[0].number: 3 z[1].number: 2 x.number: 3 y.number: 1
instead of one,
z[0].number: 3 z[1].number: 1 x.number: 3 y.number: 1
how can make second output possible? i've searched 3 days, , still no luck :(
when say:
test z[2] = {x, y};
z
holds 2 copy-constructed instances of test
. since didn't put in copy constructor, uses default, copies data members. thus, z
contains copy of x
, copy of y
. that's why changing y
doesn't change what's in z
. it's not java reference.
Comments
Post a Comment