views:

96

answers:

2
#include <iostream>

typedef struct _person
{
    std::string name;
    unsigned int age;
}Person;

int main()
{
    Person *pMe = new Person;
    pMe->age = 10;
    pMe->name = "Larson";

    std::cout << "Me " << (*pMe).age << " " << (*pMe).name.c_str() << std::endl;

    return 0;
}

Consider the above code. The members of the structures can be referenced in two ways. Eg., pMe->age or (*pMe).age. Is this just a syntactic difference or is there any functional difference available in these two approaches?

+1  A: 

Basically it's the same. However, both the dereferencing operator (*) and the pointer access operator (->) could be overloaded for class types, so it's possible to supply different behaviour for each of them. That's a very special case however, and not the case in your sample.

Alexander Gessler
+1  A: 

This is just a syntactic difference and the reason for the difference can be found here

Because the syntax for access to structs and class members through a pointer is awkward, C++ offers a second member selection operator (->) for doing member selection from pointers. Hence both lines are equivalent. The -> operator is not only easier to type, but is also much less prone to error because there are no precedence issues to worry about. Consequently, when doing member access through a pointer, always use the -> operator.

ckv