I am preparing for a C++ test and came across this code example.
In the code example below, obj is passed to SomeFunc. SomeFunc has parameter Foo obj so a copy is made which results in a Foo being created and later destroyed when SomeFunc function returns.
If you change the function signature to:
SomeFunc(Foo& obj);
or better:
SomeFunc(const Foo& obj);
problem goes away.
What is puzzling however is why the code crashes on the obj.PrintVal(); line.
I can understand how on calling SomeFunc that a new Foo is created and destroyed when the function returns, but I thought that would be isolated to the local copy of obj in SomeFunc. But when I step through in my debugger I find that the ptr of obj in main is deallocated. and so on calling obj.PrintVal() - the dereference of ptr causes segmentation fault / access violation.
Can someone please explain what is happening.
#include <iostream>
class Foo
{
public:
int *ptr;
Foo(int i) {
ptr = new int(i);
}
~Foo() {
delete ptr;
}
int PrintVal() {
std::cout << *ptr;
return *ptr;
}
};
void SomeFunc(Foo obj) {
int x = obj.PrintVal();
}
int main() {
{
Foo obj= 15;
SomeFunc(obj);
obj.PrintVal();
}
return 0;
}