Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ syntax for dereferencing class member variables

This is more of a question of syntactic elegance, but I'm learning C++ and playing around with pointers. If I have a class, Car, I can create a pointer to a new instance of that class with

Car * Audi = new Car;

If that class has a member variable weight (an unsigned int, say), I can access it with either

(*Audi).weight

or

Audi->weight

If that class has a member variable age that is itself a pointer, I can access it with either

*((*Audi).age)

or

*(Audi->age)

Is there any other way than either of these two (admittedly not particularly complicated) ways of dereferencing the pointer? I wanted to think

Audi->*age

would work, but alas it does not.

(I appreciate that accessors are usually preferable, I'm just interested.)

like image 642
badgerm Avatar asked Jun 28 '12 14:06

badgerm


2 Answers

*(Audi->age)

You don't need the parenthesis, because prefix operators have very low precedence:

*Audi->age
like image 168
fredoverflow Avatar answered Oct 28 '22 07:10

fredoverflow


No one has mentioned this way:

Audi->age[0]
like image 37
David Grayson Avatar answered Oct 28 '22 07:10

David Grayson