Different ways to call C ++ functions

I know this is a very simple question, but after a few google searches and clicking a few links, I still could not find the answer.

My question is what is the difference between "." and "->" in a function call in C ++?

For example, I have a program with two different data structures. Semaphore aaa; Bbb list;

To use the function on a semaphore, I have to do aaa.P (); but in List, I have to do List-> append (object);

I don’t quite understand why Semaphore uses .P (), whereas List uses β†’ append () when the semaphore is just a data structure containing an integer and a list.

+4
source share
6 answers

Use an operator . when you refer to members using the object itself, or a link to the object.

 struct Foo { void bar() {} }; Foo foo; Foo& fooref = foo; foo.bar(); fooref.bar(); 

Use the -> operator when you access an element through a pointer to an object. Continuing the above example

 Foo *fooptr = &foo; fooptr->bar(); (*fooptr).bar(); // same as preceding line 
+4
source

On the surface:

ab used to access element b object a .
a->b defined as equivalent (*a).b if a is a pointer type.

Additional Information:

. cannot be overloaded, but -> can be overloaded for classes (types without pointers). The return value of the -> operator is the result of applying the -> operator until the pointer type is reached.

Please note that this cannot be done with a sequence of exploits of different access-member access (try and see), even if the * (dereference) operator is overloaded. This is due to the fact that you need to "loop" on the result of evaluating the return type -> at compile time, which cannot be done manually. This is useful for creating a proxy object that behaves like a pointer to an object.

+4
source

In Foo.Bar() , Foo is a class object with Bar() .

In Foo->Bar() , Foo is a pointer to an object with Bar() .

It is not so much a question of which class uses which operator, but which operator to use depending on the context.

+2
source

. means access to an element inside an object (for data and functions). -> is the same, but it uses a pointer to an object.

For instance:

 struct abc { int xyz; } a; struct abc *pointer_to_a = &a; a.xyz = 271828; // manipulates the object directly. pointer_to_a->xyz = 314159; // manipulates the object through a pointer. 
+1
source

In addition to what others have said, foo->bar() is the same as (*foo).bar() . This is just a shortened and convenient notation. That is, if the operator -> not overloaded for foo .

0
source

As for your initial question, the reason for the difference is that Semaphore is a class type and List is a pointer type. This is a fact about your particular program, not a language. Most likely, there are some typedefs that make this structural feature of your program one that is not immediately obvious.

0
source

All Articles