C++ syntax for dereferencing class member variables

10,273

Solution 1

Syntactically, no, not unless you want to write a function or macro to do it. You could, but if you ask me, just use accessors. Also, you don't want to allocate most objects on the heap. Just declare them as type foo; or type foo = type() and let them be on the stack. You shouldn't put things on the heap with dynamic allocation unless you have a specific good reason to do so, as dynamic allocation has high overhead.

Solution 2

*(Audi->age)

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

*Audi->age

Solution 3

No one has mentioned this way:

Audi->age[0]
Share:
10,273
badgerm
Author by

badgerm

Updated on July 06, 2022

Comments

  • badgerm
    badgerm almost 2 years

    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.)