Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Class returning old values?

Tags:

c++

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 :(

like image 525
WebGL3D Avatar asked May 14 '13 19:05

WebGL3D


Video Answer


1 Answers

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.

like image 117
chris Avatar answered Oct 28 '22 22:10

chris