Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways of calling functions C++

Tags:

c++

function

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.

like image 647
krikara Avatar asked Dec 22 '22 07:12

krikara


2 Answers

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
like image 139
Praetorian Avatar answered Dec 24 '22 03:12

Praetorian


On the surface:

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.

More info:

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.

like image 41
user541686 Avatar answered Dec 24 '22 03:12

user541686