2

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?

Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34
  • Since in C there are pointers and values so to operators are used to distinguish those too. In other languages like Java you have just references. C++ leverage this duplication of this access operators and provides smart pointers (value which has some properties accessible by `.` and and pointed value accessible by `->`). – Marek R Apr 25 '23 at 10:00
  • 1
    Because its a pointer. Because the designers of the language said so. – tkausl Apr 25 '23 at 10:00
  • 1
    Because `sum_obj` is a pointer. `x->y` is the same as `(*x).y`. I suggest you read the chapter dealing with pointers in your beginner's C++ text book. – Jabberwocky Apr 25 '23 at 10:00

2 Answers2

8

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.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • 2
    Thanks for your good explanation. Now I know why I should use `->` instead of `.`. –  Apr 25 '23 at 10:10
  • Good answer. However note how the OP got an error for trying to call dot operator on a pointer. You left out that `p->x` is identical to `(*p).x` (as mentioned in the comments). It seems your answer could use one introductory sentence. – Friedrich Apr 25 '23 at 10:12
  • 3
    @Friedrich They seem to already know about `->`, as they mention it in the question. To me it reads like a question about why the language was designed this way. – HolyBlackCat Apr 25 '23 at 10:14
  • Agreed. Do they know about `(*p).x`? – Friedrich Apr 25 '23 at 10:14
0

the arrow operator -> is used to access the member variables or member functions of an object that is pointed to by a pointer. The arrow operator is used with pointers because when we use the dot operator . to access a member variable or function, the compiler will assume that we are accessing a member of an object, not a pointer to an object.

samuel potter
  • 189
  • 3
  • 13