0

I found this piece of code in the following link

http://www.tutorialspoint.com/cplusplus/cpp_copy_constructor.htm

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

where Line is defined as:

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

private:
  int *ptr;
 };

So help me understand.. What is the point in allocating memory for *ptr inside the Copy constructor ? By assigning it to *obj.ptr, essentially they are both pointing to the same locations in memory? Why should I use the new here, if it is only going to perform a shallow copy, that is copy the pointer address of the intended variable ?

Floose
  • 525
  • 2
  • 7
  • 15
  • Smells like an infinite recursion (although avoided here) –  Jan 28 '14 at 22:53
  • This is the [Rule of Three](http://stackoverflow.com/q/4172722/1553090). It's a shame that the example is so contrived. It's very unusual to allocate memory for a single `int`. – paddy Jan 28 '14 at 22:53

2 Answers2

2

This is the way for making deep copies. The pointers don't point to the same location, since you dynamically alocated ptr (so it has a it's own new location). After that your copying just the value of the pointer, by dereferencing them.

ssuljic
  • 1,081
  • 1
  • 9
  • 26
  • 1
    Not copying the value of the pointer, copying the value of the object (in this case an `int`) pointed to by the pointer. – Steve Jessop Jan 28 '14 at 22:52
1

Each Line instance has its own dynamically allocated int. The copy constructor is allocating a new int and then copying the value of the int being pointed at, it is not copying the pointer itself.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770