Hi, I am trying to figure out how copy constructors work and the code inside it. I think I understand what is happening but was hoping someone could just confirm if I am right or not, I am sort of new to allocating on the heap, and pointers and references in general. Code is below, copy constructor first, then the rest of the code if needed.
So what i think is happening in the copy constructor is :
1. the object is passed in by reference, so it has the address of the object (the object iself, not a copy).
2. Then a new int is created on a heap which has a pointer pointing at it called ptr.
3. Then, what the value ptr is pointing at (the int on the heap) is changed to what is being stored at for the location of the ptr object of the original object that was passed in
1 2 3 4 5 6
Line::Line(const Line &obj) {
cout << "Copy constructor allocating ptr." << endl;
ptr = newint;
*ptr = *obj.ptr; // copy the value
}
yes, that is pretty much correct.
a reference is not a pointer, though it acts very much like one. It may or may not be passing the original by an address (there are times when it will actually pass the variable directly, no pointers/addresses actually involved). Keep in mind that & has 2 meanings, reference and address of. A quick rule of thumb: If its on the left or a parameter, its a reference:
int &x = y;
if its on the right its address of:
int *x = &y;
This is a very tiny correction to your comment but knowing the difference will help you understand things. It has no effect on your understanding of the copy ctor, but your understanding of references.