(->) Arrow Operator And (.) Dot Operator , Class Pointer


Answer :

you should read about difference between pointers and reference that might help you understand your problem.

In short, the difference is:
when you declare myclass *p it's a pointer and you can access it's members with ->, because p points to memory location.

But as soon as you call p=new myclass[10]; p starts to point to array and when you call p[n] you get a reference, which members must be accessed using ..
But if you use p->member = smth that would be the same as if you called p[0].member = smth, because number in [] is an offset from p to where search for the next array member, for example (p + 5)->member = smth would be same as p[5].member = smth


Note that for a pointer variable x

myclass *x; 
  • *x means "get the object that x points to"
  • x->setdata(1, 2) is the same as (*x).setdata(1, 2) and finally
  • x[n] means "get the n-th object in an array".

So for example x->setdata(1, 2) is the same as x[0].setdata(1, 2).


Because by using [] like p[3] you are already dereferencing the pointer to array + index shift. After that you have to use ".", since p[3] is an object, not a pointer.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?