Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top