#include class X { public: int *i; X (int a) { i = new int; *i = a;} ~X () { delete i; } }; void print (X x) { cout << *x.i << endl; } main () { X x (15); print (x); X y (16); print (x); print (y); return 0; }
The expected output is 15, 15, 16 however, the output is 15, 16, 16 does anyone know why?? ThanksTricky C++ Class
Hi everyone,
I''ve got some question for your guys.
please see the following code
Well, I would use *(x.i) although . is a higher precedence than *, but a person could mistakenly read it as x->i. You should also pass it as a referance. It created an new X for the print function which since you don''t have a function defined creating a new X from a referance of X means the default copy constructor was used. I don''t think that will work in this case and may be the source of your problem although the copy should have the same value for i. The error is that it should point to it''s own integer. I''m not sure why it would cause this problem, but if this a supposed to be an equivalent of the code causing the actually problem it may be right on the money.
Keys to success: Ability, ambition and opportunity.
I''m not sure if i''m saying the same thing as the last guy. In the print function you are creating a copy of the object you pass as parameter. The copy is destructed at the end of the function while containing the values of the object you passed. so it deletes the i value you passed to it. The last 16 could have been any number. Its probably 16 because y.i got allocated the same adress that x.i just lost.
cmaker- I do not make clones.
November 07, 2000 04:26 PM
Even the second 16 is garbage.
To put it in yet another way, the value of i gets deleted after print() returns. You can fix it by making a copy constructor that allocates a new version of *i or by passing x by reference. You should do both to be safe.
-Mike
To put it in yet another way, the value of i gets deleted after print() returns. You can fix it by making a copy constructor that allocates a new version of *i or by passing x by reference. You should do both to be safe.
-Mike
Why is it, may I ask, that you are using a pointer (4 bytes) to an int (2 bytes) for a total of 6 bytes, when you could be using just the int and use 2? Is it because you want the ability for each instance of X to be able to access the same i? just wonderin.
farmersckn
farmersckn
Yesterday is the past, tomorrow is the future. Today is a gift, that is why we call it the present.
Hey, that''s cheating. And who does cheating hurt?
Ok, I get it now. The destructor released it.
Ok, I get it now. The destructor released it.
Keys to success: Ability, ambition and opportunity.
November 08, 2000 10:03 PM
You answered the question wrong then
Have you turned in the exam yet?
Have you turned in the exam yet?
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement