title: Explaining copy constructor example
body: <p>A copy constructor is used for many things such as when I need to use pointers or dynamically allocate memory for an object. But looking at this example at <code>tutorialpoint.com</code>:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  class Line
  {
  public:
    int getLength( void );
    Line( int len );             // simple constructor
    Line( const Line &amp;obj);  // copy constructor
    ~Line();                     // destructor
  
  private:
    int *ptr;
  };
  
  // Member functions definitions including constructor
  Line::Line(int len)
  {
  cout &lt;&lt; "Normal constructor allocating ptr" &lt;&lt; endl;
  // allocate memory for the pointer;
  ptr = new int;
  *ptr = len;
  }
  
  Line::Line(const Line &amp;obj)
  {
  cout &lt;&lt; "Copy constructor allocating ptr." &lt;&lt; endl;
  ptr = new int;
  *ptr = *obj.ptr; // copy the value
  }
  
  Line::~Line(void)
  {
  cout &lt;&lt; "Freeing memory!" &lt;&lt; endl;
  delete ptr;
  }
  int Line::getLength( void )
  {
  return *ptr;
  }
  
  void display(Line obj)
  {
     cout &lt;&lt; "Length of line : " &lt;&lt; obj.getLength() &lt;&lt;endl;
  }
  
  // Main function for the program
  int main( )
  {
     Line line(10);
  
     display(line);
  
    return 0;
  }
  </code></pre>
  
  <p>the result is :</p>
  
  <pre><code>Normal constructor allocating ptr
  Copy constructor allocating ptr.
  Length of line : 10
  Freeing memory!
  Freeing memory!
  </code></pre>
  
  <p>and when I commented out (the copy constructor) and the code inside destructor I got the same results:</p>
  
  <pre><code>Normal constructor allocating ptr
  Length of line : 10
  </code></pre>
  
  <p>So what is the difference between using the copy constructor here or not? Also why does "Freeing Memory!" occur twice?</p>