Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I should use '->' instead of '.' in a pointer of the object? [duplicate]

I agree this might be a very beginner's question, but I have no idea why I can't use '.' to access a member of a pointer to an object.

e.g.

JMP *sum_obj = new JMP("0");
JMP a;
sum_obj->number;
a.number;

sum_obj.number; // error: request for member ‘number’ in ‘sum_obj’, which is of pointer type ‘JMP*’ (maybe you meant to use ‘->’ ?)

Here, why should I use -> for the sum_obj number member?


1 Answers

In C there would be no technical reason. A non-technical reason is clarity - if you see a ->, you know that it's a pointer and can potentially be null, so you might need to check for null before dereferencing it.

In C++, there are classes that pretend to be pointers to some degree (std::unique_ptr, std::shared_ptr, std::optional). They support * and -> like pointers, but they also have their own member functions, accessible with .. Separating the notation this way avoids any possible member name conflicts, and also adds clarity.

like image 80
HolyBlackCat Avatar answered Nov 20 '25 05:11

HolyBlackCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!