first I am going to try explain what I want to do and then explain the behavior that I am experimenting
I have a main.cpp file and I have some objects, for example, x, y, z. I want to define this objects in main.cpp and pass them to a function to initialize them, and finally use them.
this is part of my code
int main(){
X* x = NULL;
Y* y = NULL;
Z* z = NULL;
function(x,y,z);
x->getX();
return 0;
}
void function (X* x, Y* y, Z* z){
x = new X();
y = new Y();
z = new Z();
}
This code results in a segmentation fault in x->getX();
. I run the program with gdb and the objects was created correctly in function()
but when the execution exits from the function
the objects was destroyed and x = y = z = 0x0.
I supposed that when you pass an object by reference to function you can modify the object's member but not the objects itself.
So, my question is how can declare a object in main, then pass it to a function to initialize and finally use it in main.
Thanks.