Pointers to Classes

A pointer to a class object is declared just like any other data type:


className identifier ;  //declare the instance of the object


className *myPtr ;  //declare a pointer of the same class as the object


myPtr = &identifier ;  //assign the address of the object instance to the pointer


className *myPtr = &identifier  //both previous two steps in one


Members of classes can be accessed using the shorthand little arrow -> member pointer dereferencing operator (aka member selection operator).


Compile & Run:

Valentino Rossi is a 33 year old Italian Moto GP Rider, who has won 9 World GP championships.
All hail the 9 times world champion! 


Troy Bayliss is a 43 year old Aussie World SuperBike Rider, who has won 3 World SuperBike championships.
All hail the 3 times world champion!






Summary of pointer and class operators:

*x pointed by x
&x address of x
x.y member y of object x
x->y member y of object pointed by x
(*x).y member y of object pointed by x (equivalent to above)
x[0] first object pointed by x
x[1] second object pointed by x
x[n] (n+1)th object pointed by x

Leave a Reply