Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Difference between (*). and ->?

Is there any difference in performance - or otherwise - between:

ptr->a();

and

(*ptr).a(); 

?

like image 929
Rachel Avatar asked Mar 18 '10 13:03

Rachel


People also ask

What is the difference in C between * & and ->?

The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. <> The * is a unary operator which returns the value of object pointed by a pointer variable. It is known as value of operator.

IS & the same as * in C?

* can be either the dereference operator or part of the pointer declaration syntax. & can be either the address-of operator or (in C++) part of the reference declaration syntax.

Why does C use ->?

The dot ( . ) operator is used to access a member of a struct, while the arrow operator ( -> ) in C is used to access a member of a struct which is referenced by the pointer in question.

What is the difference between the dot operator and ->?

Difference between Dot(.)The Dot(.) operator is used to normally access members of a structure or union. The Arrow(->) operator exists to access the members of the structure or the unions using pointers.


2 Answers

[Edit]

If the variable is defined as T* (where T is some type) then both -> and * are the same (unless ptr is null).

If the variable is an instance of a class (by value or by reference) then -> and * should behave the same (per best practice) but this requires the class to overload them the same way.

like image 98
Itay Maman Avatar answered Sep 19 '22 17:09

Itay Maman


Since you are asking for it in the comments. What you are probably looking for can be found in the Standard (5.2.5 Class member access):

3 If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2;

The compiler will produce the exact same instructions and it will be just as efficient. Your machine will not know if you wrote "->" or "*.".

like image 42
Lucas Avatar answered Sep 17 '22 17:09

Lucas