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;

c->something();

or

code c;
c.something();

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

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.

*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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.