Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The logic not to use "*" for class that memory dynamically allocated

Tags:

c++

so i'm learning c++ and i just learned about dynamically allocated memory for class. there's something that make me it feel weird.

int main()
{
    person* pOne = new person("mike", 35);
    cout << pOne << " " << pOne->getName() << endl;

    person pTwo = { "dave", 30 };
    cout << pTwo.getName() << endl;

    return 0;
}

i think that when we want to call getName() function in pOne, we should do it like *pOne->getName() because pOne hold the memory location, not the person object itself. but if i do that i'll got compiler error.

i do it with pTwo that not dynamically allocated and it work like i tought.

so, can someone explain the logic of not using "*" when trying to call function?

like image 581
FDuldul Avatar asked Nov 29 '22 22:11

FDuldul


1 Answers

The built-in operator a->b is defined as (*a).b, so the dereference is "hidden" inside the -> operator.

like image 84
Angew is no longer proud of SO Avatar answered Dec 15 '22 02:12

Angew is no longer proud of SO