title: returning a class object with a pointer
body: <p>I have a class </p>
  
  <pre><code>class Foo
  {
      public:
      char* ptr;
      Foo()  { ptr=new char [10]; }
      ~Foo()  { delete [] ptr;  }
  };
  </code></pre>
  
  <p>I have learnt that returning an object of this class is not possible as the dynamically allocated pointer is <code>delete</code> 'ed and creates a dangling pointer in the calling function</p>
  
  <p>So how can I return An object of this class??</p>
  
  <pre><code>Foo Bar ()
  {
      Foo obj;
      return obj;
  }
  </code></pre>
  
  <p>Can it be solved by  adding a copy constructor</p>
  
  <pre><code>Foo::Foo(const Foo&amp; obj)
  {
      ptr = new char [10];
      for( int i = 0 ; i &lt; 10 ;++i )
          ptr [i] = obj.ptr[i];
  } 
  </code></pre>
  
  <p>And the function as</p>
  
  <pre><code>Foo Bar ()
  {
      Foo obj;
      return Foo(obj);     //invokes copy constructor
  }
  </code></pre>
  
  <p><strong>Note</strong>  These are just representation of the actual class I want and is not created according to recommended standards (ie. Please don't tell me to use <code>std::string</code> or <code>std::vector</code>).</p>