OOPortal OOPortal


User Defined Types  «Prev 

C++ Composition of Attributes

In C++, you have a choice of three types for your attributes: as pointers, as references, or as solid objects.

Pointers: Example Code 1

If you use pointers, the class definition will look like the code below.
class Rental{
private:
  Date startDate, returnDate, actualreturnDate;
 Customer* rentedby;
 Video* itemrented;
  // remainder of class omitted
};

When you use these attributes, you will have to dereference the pointers.

References: Example Code 2

View the code below to see how references are used in C++.
 
class Rental{
private:
  Date startDate, returnDate, actualreturnDate;
Customer& rentedby;
  Video& itemrented;
  // remainder of class omitted
};

If you use references for the attributes, the class definition will look like the example shown above. You do not need to dereference references; more important, you cannot change them to refer to a different object. Pointers can be changed to point to something else. Because it makes little sense for the Rental object to change the customer who is renting or the item that is rented, references are probably a better choice than pointers for this class.

Solid objects: Example Code 3

Both pointers and references enable the class to reach an object that has been created elsewhere. If the Customer object changes during the life of this Rental object, the new values will be available to the Rental object. In contrast, a solid object is fully contained within the class, and is a private copy of the original information.

class Rental{
private:
  Date startDate, returnDate, actualreturnDate;
Customer rentedby;
Video itemrented;
// remainder of class omitted
};

View the Code below to see an example of the class definition. If the customer returns the video late, your code will add late charges to the customer's balance. You want that change to affect the real customer, somewhere outside this Rental object, not just some local copy. Using solid member variables is not the right decision for the Rental class.