There is very little difference between pointers to variables as discussed in
the section called “Pointers in C/C++” and pointers to objects. First off, we can define a pointer
p to objects of a certain class type using:
Account anAccount(5.0, 12345), *p;
p is a pointer to objects of the
class. Since the pointer is still just the storage of a memory address there is no need to
attempt any type of construction call in the creation of the pointer. When the pointer is first
created, it is not pointing to an object of the
Account class, nor is an object
Account class created. The pointer simply points at nothing (well
nothing of consequence).
If we wish to make the pointer
p point to an object of the
Account class, we could use a statement like:
Account anAccount(5.0, 12345), *p; p = &anAccount; // alternative notation would be (just like pointers to variables): Account anAccount(5.0, 12345); Account *p = &anAccount;
Previously, several methods were defined for the
Account class that
allowed operations to be applied to the account object, such as
makeWithdrawal(). How are
these methods used when dealing with pointers?
In the same way that we applied the . operator to objects we can apply the -> operator to pointers to objects. The notation is simply a - followed by a >
So for example, to demonstrate the object notation and the pointer notation:
//object notation Account anAccount = Account(35.00, 12344); anAccount.makeLodgement(20.0); anAccount.display(); //pointer notation Account testAccount = Account(5.0, 12345); Account *testPtr = &testAccount; testPtr->makeLodgement(20.0); testPtr->display();
A full source code example for this segment is listed in
The output from this example would be:
account number: 12344 has balance: 55 Euro account number: 12345 has balance: 25 Euro
testPtr->myBalance is exactly the same as
(*testPtr).myBalance, but the -> notation is a lot easier to comprehend when
combined with other operators.
© 2006 Dr. Derek Molloy (DCU).