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

or

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

 

#include <iostream>
#include <string>
using namespace std;

class Rider {
	int age, championships ;
	string nationality ;

public:
	void setValues ( int, int, string ) ; //setter

	int getAge() { return age; }
	int getChampionships() { return championships; }
	string getNationality() { return nationality; }

	void hail() { cout << "All hail the " << championships << " times world champion!" << endl << endl ; }

} bayliss ; //note declaration of Rider object called bayliss

void Rider::setValues ( int age, int championships, string nationality) {
	this -> age = age ;  //using this for the current object
	this -> championships = championships ;
	this -> nationality = nationality ;
}

int main() {

	Rider rossi ; //declare Rider object called rossi

	Rider *myPtr = &rossi ;  //assign pointer to rossi object

	myPtr->setValues ( 33, 9, "Italian") ;  //set rossi object values
	cout << "Valentino Rossi is a "  << myPtr->getAge() << " year old " ;  //display rossi object values
	cout << myPtr->getNationality() << " Moto GP Rider, who has won " ;
	cout << myPtr->getChampionships() << " World GP championships." << endl ;
	myPtr->hail() ;  //display rossi object message

	myPtr = &bayliss ;  //reassign the pointer to the bayliss object

	myPtr->setValues ( 43, 3, "Aussie") ;
	cout << "Troy Bayliss is a "  << myPtr->getAge() << " year old " ;
	cout << myPtr->getNationality() << " World SuperBike Rider, who has won " ;
	cout << myPtr->getChampionships() << " World SuperBike championships." << endl ;
	myPtr->hail() ;

	return 0 ;
}

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