Copy constructor example explanation

The copy constructor is used for many things, for example, when I need to use pointers or dynamically allocate memory for an object. But looking at this example in tutorialpoint.com:

#include <iostream>

using namespace std;

class Line
{
public:
  int getLength( void );
  Line( int len );             // simple constructor
  Line( const Line &obj);  // copy constructor
  ~Line();                     // destructor

private:
  int *ptr;
};

// Member functions definitions including constructor
Line::Line(int len)
{
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}

Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}

Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}

void display(Line obj)
{
   cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
int main( )
{
   Line line(10);

   display(line);

  return 0;
}

result:

Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!

and when I commented out (copy constructor) and the code inside the destructor, I got the same results:

Normal constructor allocating ptr
Length of line : 10

So what is the difference between using the copy constructor here or not? Also why is "Freeing up memory!" meet twice?

+5
source share
4 answers

display() , . , : , . , , , display(), , . , , ptr. , ( ). , , . @Joe : `ptr ', .

+3

.

, , , , , , .

- , , .

+4

, ++ , . , , . , - , , .

+1
source

Constructor of some type T of the form

T (const & T);

The only argument should be a const reference to an existing object of the same type. Duplicates an existing object. Used whenever a copy of the object is required. Including arguments in functions, results returned from functions. Problems with arrays based on pointers in C ++: - No range checking. Cannot compare with == No array assignment (array names are constant pointers). If an array is passed to a function, size must be passed as a separate argument.

0
source

All Articles