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!

5
  • 2
    So this is not C. Commented Mar 10, 2017 at 13:45
  • 3
    Did you study what -> mean? Commented Mar 10, 2017 at 13:46
  • You might want to step back and find a good book. Commented Mar 10, 2017 at 13:47
  • It seems to me that you're not noticing that "." and "->' are different operators. Commented Mar 10, 2017 at 13:47
  • 5
    var->Foo() is (*var).Foo() Commented Mar 10, 2017 at 13:47

2 Answers 2

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(); 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.