title: Declare object outside function, pass it as reference and then create it inside function
body: <p>first I am going to try explain what I want to do and then explain the behavior that I am experimenting </p>
  
  <p>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.</p>
  
  <p>this is part of my code</p>
  
  <pre><code>int main(){
      X* x = NULL;
      Y* y = NULL;
      Z* z = NULL;
  
      function(x,y,z);
  
      x-&gt;getX();
  
      return 0;
  }
  
  void function (X* x, Y* y, Z* z){
      x = new X();
      y = new Y();
      z = new Z();
  }
  </code></pre>
  
  <p>This code results in a segmentation fault in <code>x-&gt;getX();</code>. I run the program with gdb and the objects was created correctly in <code>function()</code> but when the execution exits from the <code>function</code> the objects was destroyed and x = y = z = 0x0.</p>
  
  <p>I supposed that when you pass an object by reference to function you can modify the object's member but not the objects itself.</p>
  
  <p>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.</p>
  
  <p>Thanks.</p>