Logic does not use "*" for a class, dynamically allocated memory

so I learn C ++ and I just found out about dynamically allocated memory for a class. there is something that makes me 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 the getName () function in pOne, we should do it like this *pOne->getName()because pOne holds the memory cell, not the person object itself. but if I do this, I will get a compiler error.

I do this with pTwoone that is not dynamically allocated, and it works like I tought.

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

+4
source share
4 answers

a->b (*a).b, "" ->.

+11

-> - : a->foo (*a).foo. , ->, .

+6

pTwo, , , . , - "*" ?

, , , :

struct Foo { void bar(); };

Foo f; // type of f is Foo
f.bar(); // access on type Foo is through .
Foo *pf = &f; // type of pf is Foo*
pf->bar(); // derefence and access on type Foo* is through ->
(*pf).bar(); // the same as above and since type of *pf is Foo we can use .
(&f)->bar(); // type of &f is Foo*, so we can use ->
(*(&f)).bar(); // crazy stuff
+2

, .

:

person *pOne = new person("mike", 35);

:

person* pOne = new person("mike", 35);

, , person* ( person), pOne.

, pOne, *pOne.

, C, , " person at *pOne". : (*pOne).getName() . , *pOne person — , ( ) .

The key point here is that ->(as in pOne->getName()) does dereferencing for you. Writing (*pOne)->getName()will do this twice.

Your last example pTwo.getName()is simply accessing an object with a swamp standard.

+1
source

Source: https://habr.com/ru/post/1693921/


All Articles