1.)SOLVED In the code below is &a the address of the newly created object a? What is the relationship between A and &a in that line?
1 2 3 4 5 6 7 8 9
#1 -SOLVED
A a; //access member through object member
a.item_a = 46;
A * n_ptr = &a; //access member through pointer to object instance
n_ptr->item_a = 101;
LAST QUESTION n the following statement I am ignoring the -> on purpose to ask a question abt:
(*n_ptr).value_1 = 5;
To what is n_ptr being dereferenced to? An object address?
I understand that -> dereferences and takes care of this for you, but I'd like to know as a thought exercise.
code:
1 2
A * n_ptr = &a; <SOLVED>
A * t_ptr = new A();<SOLVED>
3.) <SOLVED>In code above, is the top statement creating a pointer to an existing object(a)?
<SOLVED<In the bottom statement is the pointer pointing to a newly created object (A)?
When you have a pointer to an object instance (MyObject* pObject = new MyObject();), you need to dereference the pointer, before you can access the object members.
Trying to "think like the machine" why is it necessary to dereference the pointer before accessing object members?
to access actual object at this address you need dereference a pointer.
But you are dereferencing the address, which retrieves the value at that address, not the address itself. At least conventional:
1 2 3
value foo = 500;
int * n_ptr = &foo;
cout<<*n_ptr;
500
When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.