2

since I am currently learning pointers in C++, I am wondering about the syntax. So when I want to use a pointer on an object, I do not have to dereference it, in order to access the class attributes. When I just want to use a pointer on a simple variable, I have to use * for changing its values.

So why do I not have to use the * for the object? Because so I thought I would just change the memory address.

Object:

int age = 20;
User John(age);    
User *ptrUser = &John;

ptrUser->printAge(); // 20 (why no *ptrUser->printAge()  ??? )
cout << ptrUser // 0x123456...

Variables:

int a = 10;
int *ptrA = &a;   
*ptrA = 20;  
cout << a // 20

Thank you very much!

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
André
  • 351
  • 1
  • 5
  • 19

2 Answers2

7

You have to dereference the pointer, the -> operator is just syntactic sugar for dereference-and-member-access:

Instead of

ptrUser->printAge();

you could write

(*ptrUser).printAge();
alain
  • 11,939
  • 2
  • 31
  • 51
0

There can actually be two things:

  1. You aren't aware about the -> operator:

As @alain pointed out in his answer, -> is mere syntactic sugar and can be replaced with a * and . as:

(*ptrUser).printAge();
  1. You are aware about the -> operator and wondering why not *ptrUser->printAge():

Here, when you say *ptrUser = &John;, you are storing the address of John in a pointer variable called ptrUser. In other words, ptrUser points to John. So, when you want to access the member function printAge() of John, you can simply do:

ptrUser->printAge();

because ptrUser is already pointing to John.

Hope this is helpful.

Community
  • 1
  • 1
abhishek_naik
  • 1,287
  • 2
  • 15
  • 27