Why do pointers use -> instead of .? [duplicate] - c++

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why does C have a distinction between -> and . ?
Lets say that I have this structure:
struct movies
{
string title;
int year;
} my_movie, *ptrMovie;
Now I access my_movie like this: my_movie.year = 1999; Now to access a pointer I must do this: ptrMovie->year = 1999;
Why do pointers use the -> operator and normal data types use the . operator? Is there any reason they couldn't both use the . operator?

The . operator accesses a member of a structure and can operate only on structure variables.
If you want to do this to a pointer, you first need to dereference the pointer (using *) and then access the member (using .). Something like
(*ptrMovie).year = 1999
The -> operator is a shorthand for this.

The . operator is only valid for a struct or class. A pointer is not a struct or class, so you need to dereference your pointer to get the struct/class it is pointing to like this
(*ptrMovie).year
The member operator . has a higher precedence than the dereference operator *, so you need to enclose the dereferencing operation in parenthesis. Or you could do this
ptrMovie->year
Both are equivalent. The '->' operator is a shortcut for dereferencing your pointer and then accessing a struct member. It is less typing and a little nicer to use in my opinion. Apparently most people agree with me because that is the standard way to access struct members from a pointer to the struct in most code that I've seen. You especially appreciate the difference when you have to do multiple levels of indirection:
ptrToStruct->memberPtr->subMemberPtr->subsubPtr->subsubsubPtr->x
(*(*(*(*(ptrToStruct).memberPtr).subMemberPtr).subsubPtr).subsubsubPtr).x
Both of those statements are equivalent, but the first is easier to work with.

If they both used . how could you differentiate between the pointer and the actual object?
To me:
->
Reminds me of an arrow which points to something, so I find it great that -> is used.
Instead of typing (*myPointer). it is simplier to use myPointer->

Related

Using dot (.) operator instead of -> operator C++

Let's say I define a pointer structure called date_ptr of a structure already defined, the following way:
Date *date_ptr = new Date[10]
Essentially this is an array of structures containing objects of type Date. Now let's say I wanted to set the month of each structure in the array doing:
date_ptr[0].month = new int(10);
date_ptr[1].month = new int(3);
My question is as follows: am I allowed to set the month variable of each structure using the dot operator instead of the -> even though date_ptr is a pointer to the structure. If so, does this cause any problems? Or is it better (or mandatory) to use the -> operator?
In your case, data_ptr is a pointer, but data_ptr[0] is not a pointer, but a object of type Date. Thus you can only use dot (.) but not -> to access Date's fields.
date_ptr is a pointer to structure but date_ptr[0] is a reference to a structure. That's because date_ptr[0] is the same as *(date_ptr+0). So it's mandatory to use ..
Careful, that's an array containing 0s of type Date *. In particular, the following code will segfault without proper initialization.
Anyway to answer you, -> is just syntactic sugar for equivalent code with .. You don't need to use it, you can simply write date_ptr->month=0; and it will compile. Or (date_ptr+1)->month=0; for the second element.
Do you mean the following? This would work.
Date * end_ptr = date_ptr + 10;
for (Date * ptr = date_ptr; ptr != end_ptr; ++ptr)
ptr->month = 1;
Be warned not do do this if polymorphism is involved or you'll encounter a bad surprise.

About struct and pointer in C++ [duplicate]

This question already has answers here:
What is the difference between the dot (.) operator and -> in C++? [duplicate]
(14 answers)
Closed 9 years ago.
I would like to create a linked list.
For the following code:
struct sampleStruct
{
int a;
sampleStruct *next = NULL;
};
sampleStruct *sample = new sampleStruct;
What is the difference between sample.next and sample->next?
Okay to explain it in a more complete way. The most other guys had already wrote that you have to use '->' when ever you have a pointer. But you could also do this with '.', to do this you must respect the priority of the operators. We need the '*' to get the content of the pointer, but this has a lower priority than the '.', so you must write it into brackets to give it a higher priority, so when you want to do this with a '.' you have to wrote:
(*sample).next
and you see this is a complex syntax, to do this in a more easy way the '->' was introduced. With it you could write code in a more comfortable way.
So this is is equal to the example and it looks much better.
sample->next
Since sample is a pointer, there can't be any way to access a data member through . rather than the indirection operator ->. For example, this won't compile:
sample.next; // error: member reference type 'sampleStruct *' is a pointer;
// maybe you meant to use '->'?
The error actually speaks for itself.

Difference between Pointer->Call() and (*Pointer).Call() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
ptr->hello(); /* VERSUS */ (*ptr).hello();
I am learning C++ and my question is if there is any difference between using the arrow operator (->) or dereferencing the pointer * for calling a function.
These two cases illustrate my question.
Class* pointer = new Class();
(*pointer).Function(); // case one
pointer->Function(); // case two
What is the difference?
If the operators * and -> aren't overloaded, both versions accomplish the same.
Given
Class* pointer = new Class();
Then
(*pointer).Function(); // case one
dereferences the pointer, and calls the member function Function on the referred to object. It does not use any overloaded operator. Operators can't be overloaded on raw pointer or built-in type arguments.
pointer->Function(); // case two
This does the same as the first one, using the built-in -> because pointer is a raw pointer, but this syntax is better suited for longer chains of dereferencing.
Consider e.g.
(*(*(*p).pSomething).pSomethingElse).foo()
versus
p->pSomething->pSomethingElse->foo()
The -> notation is also more obvious at a glance.

c++ question, about * and ->

when I have a pointer like:
MyClass * pRags = new MyClass;
So i can use
pRags->foo()
or
(*pRags).foo()
to call foo.
Why these 2 are identical? and what is *pRags?
Thank you
Why are these two identical?
They are equivalent because the spec says they are equivalent. The built-in -> is defined in terms of the built-in * and ..
What is *pRags?
It is the MyClass object pointed to by pRags. The * dereferences the pointer, yielding the pointed-to object.
For more information, consider picking up a good introductory C++ book.
In addition to the other answers, the '->' is there for convenience. Dereferencing a pointer to an object every time you access a class variable for function is quite ugly, inconvenient, and potentially more confusing.
For instance:
(*(*(*car).engine).flux_capacitor).init()
vs
car->engine->flux_capacitor->init()
pRags->foo() is defined as syntactic sugar that is equivalent to (*pRags).foo().
the * operator dereferences a pointer. That is, it says that you're operating on what the pointer points to, not the pointer itself.
The -> is just a convenient way to write (*).. and *pRags is the object at the address stored in pRags.
Yes they are identical. -> was included in C (and thus inherited into C++) as a notational convenience.
* in that context is used to dereference a pointer.
Unary * is known as the dereferencing operator. Dereferencing a pointer turns a T* into a T&; dereferencing an object invokes that object type's unary operator* on that object value if one is defined, or gives an error otherwise.
(*pRags) that goes through the pointer pRags and get you whole object, so on that you could use regular dot notation . .
pRags is a pointer of type MyClass. Just like you can have pointers for primitive data types, e.g. int ptr, you can also have pointers to objects and in this case represented by pRags. Now accessing the object "members" is done using the arrow operator (->) or you can use the "." and dereference "*" to access the object's member values. Here a member is a variable inside MyClass. So, foo() would have a definition inside MyClass.

What is the difference between the dot (.) operator and -> in C++? [duplicate]

This question already has answers here:
What can I use instead of the arrow operator, `->`?
(7 answers)
Closed 5 years ago.
What is the difference between the dot (.) operator and -> in C++?
foo->bar() is the same as (*foo).bar().
The parenthesizes above are necessary because of the binding strength of the * and . operators.
*foo.bar() wouldn't work because Dot (.) operator is evaluated first (see operator precedence)
The Dot (.) operator can't be overloaded, arrow (->) operator can be overloaded.
The Dot (.) operator can't be applied to pointers.
Also see: What is the arrow operator (->) synonym for in C++?
For a pointer, we could just use
*pointervariable.foo
But the . operator has greater precedence than the * operator, so . is evaluated first. So we need to force this with parenthesis:
(*pointervariable).foo
But typing the ()'s all the time is hard, so they developed -> as a shortcut to say the same thing. If you are accessing a property of an object or object reference, use . If you are accessing a property of an object through a pointer, use ->
Dot operator can't be overloaded, arrow operator can be overloaded. Arrow operator is generally meant to be applied to pointers (or objects that behave like pointers, like smart pointers). Dot operator can't be applied to pointers.
EDIT
When applied to pointer arrow operator is equivalent to applying dot operator to pointee e.g. ptr->field is equivalent to (*ptr).field.
The arrow operator is like dot, except it dereferences a pointer first. foo.bar() calls method bar() on object foo, foo->bar calls method bar on the object pointed to by pointer foo.
The . operator is for direct member access.
object.Field
The arrow dereferences a pointer so you can access the object/memory it is pointing to
pClass->Field
pSomething->someMember
is equivalent to
(*pSomething).someMember
Use -> when you have a pointer.
Use . when you have structure (class).
When you want to point attribute that belongs to structure use .:
structure.attribute
When you want to point to an attribute that has reference to memory by pointer use -> :
pointer->method;
or same as:
(*pointer).method
The target.
dot works on objects; arrow works on pointers to objects.
std::string str("foo");
std::string * pstr = new std::string("foo");
str.size ();
pstr->size ();
Note that the -> operator cannot be used for certain things, for instance, accessing operator[].
#include <vector>
int main()
{
std::vector<int> iVec;
iVec.push_back(42);
std::vector<int>* iVecPtr = &iVec;
//int i = iVecPtr->[0]; // Does not compile
int i = (*iVecPtr)[0]; // Compiles.
}
It's simple, whenever you see
x->y
know it is the same as
(*x).y
The -> is simply syntactic sugar for a pointer dereference,
As others have said:
pointer->method();
is a simple method of saying:
(*pointer).method();
For more pointer fun, check out Binky, and his magic wand of dereferencing:
http://www.youtube.com/watch?v=UvoHwFvAvQE
The simplest difference between the two is that "->" dereferences a pointer before it goes to look at that objects fields, function etc. whereas "." doesn't dereference first. Use "->" when you have a pointer to an object, and use "." when you're working with the actual instance of an object.
Another equivalent way of wrinting this might be to use the dereferencing "*" on the pointer first and then just use the ".". We skip middleman by using "->".
There are other differences, but the other answers have covered this extensively.
If you have a background in Java this might confuse you, since, in Java, everything is pointers. This means that there's no reason to have symbol that doesn't dereference your pointer first. In c++ however you gotta be a little more careful with remembering what is and what isn't a pointer, and it might be a good idea to label them with the prefix "p_" or simply "p".
The . (dot) operator is usually used to get a field / call a method from an instance of class (or a static field / method of a class).
p.myField, p.myMethod() - p instance of a class
The -> (arrow) operator is used to get a field / call a method from the content pointed by the class.
p->myField, p->myMethod() - p points to a class
The -> operator is used when we are working with a pointer and the dot is used otherwise.
So if we have a struct class like:
struct class{ int num_students; int yr_grad; };
and we have an instance of a class* curr_class (class pointer), then to get access to number of students we would do
cout << curr_class->num_students << endl;
In case we had a simple class object , say class_2016, we would do
cout << class_2016.num_students << endl;
For the pointer to class the -> operator is equivalent to
(*obj).mem_var
Note: For a class, the way to access member functions of the class will also be the same way