I know C, but I'm not good at C++.
The following code will crash (In getval(), using reference as a parameter is ok).
And value of *p
is changed after first cout
statement. It looks there is some overwriting caused by out of bound of memory.
My question is why it crashed (or why its value is changed). It's 'call by value' of object, so should it work anyway?
class myclass {
int *p;
public:
myclass(int i);
~myclass() { delete p; }
int getval(myclass o);
};
myclass::myclass(int i)
{
p = new int;
if (!p) {
cout << "Allocation error\n";
exit(1);
}
*p = i;
}
int myclass::getval(myclass o)
{
return *o.p;
}
int main()
{
myclass a(1), b(2);
cout << a.getval(a) << " " << a.getval(b) << endl;
cout << b.getval(a) << " " << b.getval(b) << endl;
return 0;
}