I know this is a very basic question, but after a few google searches and clicking on multiple links, I still couldn't find an answer.
My question is what is the difference between the " . " and the " -> " in function calling in C++ language?
For example, I have a program with 2 different data structures. Semaphore aaa; List bbb;
To use a function on semaphore, I have to do aaa.P(); but on List, I have to do List->append(object);
I don't quite understand why Semaphore uses .P() whereas List uses ->append() when semaphore is just a data structure containing an integer and a list.
Use the . operator when you're accessing members using the object itself, or a reference to the object.
struct Foo
{
  void bar() {}
};
Foo foo;
Foo& fooref = foo;
foo.bar();
fooref.bar();
Use the -> operator when you're accessing a member via a pointer to the object. Continuing the above example
Foo *fooptr = &foo;
fooptr->bar();
(*fooptr).bar();  // same as preceding line
                        a.b is used for accessing member b of object a.a->b is defined to be eqivalent to (*a).b if a is a pointer type.
The . can't be overloaded, but -> can be overloaded for classes (non-pointer types). The return value of the -> operator is the result of applying the -> operator until a pointer type is reached.
Note that this is impossible to do with a sequence of dereference-followed-by-member-access operations (try it and see), even though the * (dereference) operator is overloadable. This is because you need to "loop" over the result of evaluating the return type of -> at compile-time, which is impossible to do manually. It's useful for making a proxy of an object that behaves like a pointer to the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With