Hello. I have been programming for a while now and am ok but for some reason i can never figure out weather or not to do something like this

code * c;



code c;

no where has explained that to me, but ive kept on trucking still. Can someone explain that to me.

5 Years
Discussion Span
Last Post by WaltP

x->someMemberVariable is for accessing a member variable/function when x is a pointer to an object.

x.someMemberVariable is for accessing a member variable/function when x is the object, not a pointer to the object.

x->someMemberVariable is shorthand for (*x).someMemberVariable

Use x->someMemberVariable when your x is a pointer to an object, use x.someMemberVariable when x is an object, not a pointer to an object.

Edited by Moschops: n/a


*c->something(); is the same as (*c.)something(); it tells to evaluate the pointer part first just like 2+2*2 us different from (2+2)*2. You can use () instead of -> but -> looks better


Rule of thumb:

When using pointers, if possible, use the arrow operator (->)
When not using pointers, use the dot operator ( . )


>>I have been programming for a while now

Taking you on your word, I would assume that the explanations of the previous posters isn't what you were looking for, because if you have been "programming for a while" you definitely knew this already. Right? I'm sure your question is not about the difference between a dot and an arrow in C++ (because you would surely have found tons of resources explaining that in way more details than you could imagine).

So, I'm guessing you are asking why would someone choose to use an object via a pointer to it, or to use an object directly. If it is so, you need to clarify the question more. Do you mean any one of these:
- "dynamically allocated objects" versus "stack-allocated objects"
- difference between accessing members from an object-pointer or an object
- pass-by-reference versus pass-by-value
- ...

The example code you posted doesn't really tell much (especially since the first one is erroneous in any case).


Another rule of thumb:

Add to you code cout << "ptr-> " << struct->member << "\ndot. " << struct.member << '\n'; Which one outputs correctly? That's the one to use. And figure out why. In no time you'll understand it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.