Our
Our

Reputation: 1035

Pointer assignments in a copy constructor

I'm using the book Programming with objects by Avinash C. KAK, and in the page 452, it says constructs a copy constructor method as

class X{
int * ptr;
int size;
public:
X(const X & xobj)
{
    size = xobj.size;
    ptr = new int [size];
    for(int i = 0; i < size; i++)
    {
        ptr[i] = xobj.ptr[i];
    }   
}
}

Then it uses as

X x1;
X x2 = x1;

But what I did not understand is that first it allocates memory for the x2.ptr and then assigns the memory address of x1.ptr to x2.ptr, which contradicts with the purpose of having a copy constructor method and the newly allocated memory is now not being used at all, so what am I missing ?

Upvotes: 0

Views: 85

Answers (1)

Akira
Akira

Reputation: 4473

If you have a pointer to a newly allocated array like:

ptr = new int[size];

then you can index it in the same way as the arrays:

ptr[1] = 3; // equivalent to: *(ptr + 1) = 3

So, as it's a copy constructor it copies the content of memory pointed by xobj.ptr to the newly allocated memory pointed by ptr.

Upvotes: 1

Related Questions