Defining Object Relationships


For the remainder of this chapter, you will see how to define relationships between objects in a Visual C++ application. Visual C++ applications typically contain many objects. These objects communicate with each other to achieve the overall functionality needed in the application.

To illustrate object relationships, you will add a new class named LoyaltyScheme to your credit card application. The LoyaltyScheme class will allow credit card owners to accrue bonus points when they use their credit card. The bonus points act as a reward for the customer’s loyal use of the credit card.

When a CreditCardAccount object is first created, it will not have a LoyaltyScheme object. The LoyaltyScheme object will be created when CreditCardAccount reaches 50 percent of its credit limit. Subsequently, every $10 spent using the credit card will accrue one bonus point in the LoyaltyScheme object, as long as the account is above the 50 percent mark. When the CreditCardAccount object is finally destroyed, the LoyaltyScheme object must also be destroyed. The following figure shows the lifetimes of the CreditCardAccount and LoyaltyScheme objects.

click to expand

To achieve this functionality, you will complete the following exercises:

  • Define the LoyaltyScheme class

  • Implement the LoyaltyScheme class

  • Create, use, and destroy LoyaltyScheme objects

  • Test the application

Defining the LoyaltyScheme Class

In this exercise, you will define the LoyaltyScheme class in a new header file named LoyaltyScheme.h.

  1. Continue using the project from the previous exercise.

  2. Select the Project menu, and then choose Add New Item.

  3. In the Add New Item dialog box, select the template Header File (.h). In the Name field, type LoyaltyScheme.h and click Open.

  4. Type the following code in the header file to define the LoyaltyScheme class:

    class LoyaltyScheme { public: LoyaltyScheme(); // Constructor ~LoyaltyScheme(); // Destructor void EarnPointsOnAmount(double amountSpent); // Earn // one point per $10 spent void RedeemPoints(int points); // Redeem points int GetPoints(); // Return the value of // totalPoints private: int totalPoints; // Total points accrued so far };

  5. Build the program, and fix any compiler errors.

Implementing the LoyaltyScheme Class

In this exercise, you will implement the LoyaltyScheme class in a new source file named LoyaltyScheme.cpp.

  1. Continue using the project from the previous exercise.

  2. Select the Project menu item, and then choose Add New Item.

  3. In the Add New Item dialog box, select the template C++ File (.cpp). In the Name field, type LoyaltyScheme.cpp and click Open. Visual Studio .NET creates an empty source file.

  4. Add two #include statements at the start of the file, as shown here:

    #include "stdafx.h"  #include "LoyaltyScheme.h"
  5. Add the following code to expose the System namespace:

    #using <mscorlib.dll> using namespace System;
  6. Implement the LoyaltyScheme constructor and destructor as follows:

    LoyaltyScheme::LoyaltyScheme() { Console::WriteLine(S"Congratulations, you now qualify for" S" bonus points"); totalPoints = 0; } LoyaltyScheme::~LoyaltyScheme(void) { Console::WriteLine(S"Loyalty scheme now closed"); }

  7. Implement the EarnPointsOnAmount member function as follows:

    void LoyaltyScheme::EarnPointsOnAmount(double amountSpent) { int points = (int)(amountSpent/10); totalPoints += points; Console::Write(S"New bonus points earned: "); Console::WriteLine(points); }

    The syntax (int)(amountSpent/10) divides the amount spent by 10 and converts the value to an int data type.

  8. Implement the RedeemPoints member function as follows:

    void LoyaltyScheme::RedeemPoints(int points) { if (points <= totalPoints) { totalPoints -= points; } else { totalPoints = 0; } }

    This function enables the user to redeem some or all of the accrued bonus points.

  9. Implement the GetPoints member function as follows:

    int LoyaltyScheme::GetPoints() { return totalPoints; }
  10. Build the program, and fix any compiler errors.

Creating, Using, and Destroying LoyaltyScheme Objects

In this exercise, you will extend the CreditCardAccount class to support the loyalty scheme functionality.

  1. Continue using the project from the previous exercise.

  2. Open CreditCardAccount.h. At the start of the file, add a #include directive as follows:

    #include "LoyaltyScheme.h"

    This will enable you to use the LoyaltyScheme class in this header file.

  3. Add a private data member to the CreditCardAccount class, as follows:

    LoyaltyScheme * ptrLoyaltyScheme; // Pointer to a // LoyaltyScheme object

    This pointer defines an association between a CreditCardAccount object and a LoyaltyScheme object.

  4. Add a public member function to the CreditCardAccount class as follows:

    void RedeemLoyaltyPoints();

    This function acts as a wrapper to the RedeemPoints function in the LoyaltyScheme class. When you want to redeem loyalty points, you call RedeemLoyaltyPoints on your CreditCardAccount object. This function will call RedeemPoints on the underlying LoyaltyScheme object to do the work.

    Note

    Relying on a member’s existing functionality is an example of delegation. The CreditCardAccount object delegates the RedeemPoints operation to the LoyaltyScheme object.

  5. Open CreditCardAccount.cpp, and find the CreditCardAccount constructor. Add the following statement in the constructor body:

    ptrLoyaltyScheme = 0; 

    This statement sets the ptrLoyaltyScheme pointer to 0 initially. Zero is a special value for a pointer because it indicates that the pointer doesn’t point to a real object yet. (The LoyaltyScheme object won’t be created until the credit card balance reaches 50 percent of the credit limit.)

  6. Modify the MakePurchase function as follows to accrue bonus points when the credit card balance reaches 50 percent of the credit limit:

    bool CreditCardAccount::MakePurchase(double amount) { if (currentBalance + amount > creditLimit) { return false; } else { currentBalance += amount; // If current balance is 50% (or more) of credit limit... if (currentBalance >= creditLimit / 2) { // If LoyaltyScheme object doesn’t exist yet... if (ptrLoyaltyScheme == 0) { // Create it ptrLoyaltyScheme = new LoyaltyScheme(); } else { // LoyaltyScheme already exists, // so accrue bonus points ptrLoyaltyScheme->EarnPointsOnAmount(amount); } } return true; } }

  7. Implement the RedeemLoyaltyPoints function as follows. RedeemLoyaltyPoints is a new member function that enables the user to redeem some or all of the loyalty points in the associated LoyaltyScheme object.

    void CreditCardAccount::RedeemLoyaltyPoints() { // If the LoyaltyScheme object doesn’t exist yet... if (ptrLoyaltyScheme == 0) { // Display an error message Console::WriteLine(S"Sorry, you do not have a " S"loyalty scheme yet"); } else { // Tell the user how many points are currently available Console::Write(S"Points available: "); Console::Write( ptrLoyaltyScheme->GetPoints() ); Console::Write(S". How many points do you want "  S" to redeem? "); // Ask the user how many points they want to redeem String * input = Console::ReadLine(); int points = input->ToInt32(0); // Redeem the points ptrLoyaltyScheme->RedeemPoints(points); // Tell the user how many points are left Console::Write(S"Points remaining: "); Console::WriteLine( ptrLoyaltyScheme->GetPoints() ); } }

    Note

    It’s important to test the ptrLoyaltyScheme pointer before you use it. If you forget to test the pointer and the pointer is still 0, your program will cause a null pointer exception at run time. This is a very common error in C++ applications.

  8. Add the following statement to the CreditCardAccount destructor:

    delete ptrLoyaltyScheme;

    This statement deletes the LoyaltyScheme object because it’s no longer needed.

    Note

    When you use delete, you do not need to test for a null pointer. The delete operator has an internal null pointer test.

  9. Build the program, and fix any compiler errors.

Testing the Application

In this exercise, you will modify the code in CreditOrganizer.cpp to test the loyalty scheme functionality.

  1. Continue using the project from the previous exercise.

  2. Open CreditOrganizer.cpp. Modify the _tmain function as follows:

    Console::WriteLine(S"Creating account object"); CreditCardAccount * account1; account1 = new CreditCardAccount(12345, 2000); Console::WriteLine(S"\nMaking a purchase (300)"); account1->MakePurchase(300); Console::WriteLine(S"\nMaking a purchase (700)"); account1->MakePurchase(700); Console::WriteLine(S"\nMaking a purchase (500)"); account1->MakePurchase(500); Console::WriteLine(S"\nRedeeming points"); account1->RedeemLoyaltyPoints(); Console::WriteLine(S"\nDeleting account object"); delete account1;
  3. Build the program, and fix any compiler errors.

  4. Run the program. The program creates a CreditCardAccount object and makes various purchases. Once the credit card balance reaches $1,000, a LoyaltyScheme object is created. Subsequent purchases accrue a loyalty point for every $10 spent.

  • When you try to redeem loyalty points, the program tells you how many points are available and asks how many you want to redeem. Enter a value such as 36. The program tells you how many points are left.

    At the end of the program, the CreditCardAccount object is deleted. The associated LoyaltyScheme object is deleted at the same time.

    The following figure shows the messages displayed on the console during the program.

    click to expand




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net