3.03 Classes and Pointers


Classes and Pointers

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;

So, pointer p is a pointer to objects of the Account 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 of the 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 display()makeLodgement and 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 BasicAccountWithPointers.cpp.

The output from this example would be:

 account number: 12344 has balance: 55 Euro
 account number: 12345 has balance: 25 Euro

Note that testPtr->myBalance is exactly the same as (*testPtr).myBalance, but the -> notation is a lot easier to comprehend when combined with other operators.


These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way.
ċ
BasicAccountWithPointers.cpp
(1k)
Derek Molloy,
8 Oct 2013, 14:25
Comments