q: objects and member access

Jan 9, 2016 at 4:13pm
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)?

4) What are these specifically called: (.) (->)

Thx in advance
Last edited on Jan 10, 2016 at 7:39pm
Jan 9, 2016 at 4:17pm
(*n_ptr).value_1 = 5;

n_ptr is dereferenced to a object declared on line 2
Jan 9, 2016 at 4:55pm
Sorry, which line, where?
Jan 9, 2016 at 5:10pm
Sorry, I meant line 3.
A a; is declared on line 3 in your first example.

line numbers as on the left of example you posted.
Last edited on Jan 9, 2016 at 5:11pm
Jan 9, 2016 at 7:59pm
Thx CK

Ok that is true.

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?
Jan 9, 2016 at 9:08pm
why is it necessary to dereference the pointer before accessing object members

because pointer stores memory address, to access actual object at this address you need dereference a pointer.

I would recommend you to read this post for more information:
http://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean
Jan 10, 2016 at 5:00pm
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.


What is the result? Data, chracter, address?
Last edited on Jan 10, 2016 at 6:43pm
Topic archived. No new replies allowed.