Reputation: 41
I’m reading the C++ Primer. There is a little confusion I encountered in the ‘const’ subsection and I really hope someone can help me clarifying it.
Here is paraphrasing from the book:
Among the operations that don’t change the value of an object is initialization— when we use an object to initialize another object, it doesn’t matter whether either or both of the objects are consts:
int i = 42;
const int ci = i; // ok: the value in i is copied into ci
int j = ci; // ok: the value in ci is copied into j
Although ci is a const int, the value in ci is an int. The constness of ci matters only for operations that might change ci. When we copy ci to initialize j, we don’t care that ci is a const. Copying an object doesn’t change that object. Once the copy is made, the new object has no further access to the original object.
Every sentence is clear except for the last one:
Once the copy is made, the new object has no further access to the original object.
My confusion is: In this context, what is new object, what is original object and why does the new object have no further access to the original object.
I hope I made my point clear. Thanks!
Upvotes: 1
Views: 100
Reputation: 141
objects are instances of classes as represented in memory. You will encounter much more about objects when you get deeper into C++ and OOD. All you need to know is when you create a copy like this:
int j = ci;
you are creating a second instance of the int class, which resides at a different memory address and has its own value. This is called a "deep copy", and that is the reason (non-const) j is still const correct. No matter what happens to j (new object) after this, ci (original object) will remain unchanged. I hope that helps, don't get discouraged as again you will be spending a lot of time on OOD and object principles.
Upvotes: 1
Reputation: 249093
what is new object, what is original object
The new object is the one which has just been declared and constructed. For example:
SomeType newObj = originalObj;
why does the new object have no further access to the original object
newObj
has no way to "look again" at originalObj
, for example it cannot find out when originalObj
has changed, nor can it change originalObj
. But if SomeType
's constructor takes originalObj
by reference, it actually can access originalObj
any time, if it stores the reference or a pointer to it inside newObj
.
Upvotes: 0