Computing Concepts with C++ Essentials
Laboratory Notebook
Chapter 8 - Classes

Cay S. Horstmann
Geof Pawlicki

Your name:
Your email address:
Your student ID number:

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.


Lab Objectives

To gain experience with


R1. Discovering classes

In each of the following examples, locate and describe those conceptually related procedures and data elements that can be combined into a single class.

/* NAME    : opt_prix.cpp
   PURPOSE : Routine to calculate the optimum price for theater ticket 
             based on data from preview showings in different cities
*/

#include "ccc.h"
             
int main()
{  bool more = true;
   string answer = "";
   int number_sold = 0;
   int best_number = 0;
   float unit_price = 0.0;
   float best_price = 0.0;
   string city = "";
   string best_city = "";   
   
   while (more)
   {  cout << "Number sold: ";
      cin >> number_sold;
   
      cout << "Unit Price: ";
      cin >> unit_price;

      cout << "City : ";
      cin >> city;

      if (( number_sold * unit_price) > (best_number * best_price))
      {   best_number = number_sold;
          best_price = unit_price;
                  best_city = city;
      }
  
      cout << "More data ( Y / N )? ";
      cin >> answer;
      if (uppercase(answer) != 'Y') 
      {   more = false;
      }
   }

   cout << best_number * best_price << " dollars generated on sale of " <<
      best_number << " tickets at " << best_price << " per ticket in " << city << "\n";
   return EXIT_SUCCESS;
}

/*  NAME:    vitl_sgn.cpp 
    PURPOSE: Main program to record general patient information before a physical examination
*/

#include "ccc.h"

const int LO = 0; 
const int HI = 200;

void pulse(int& pulse_rate)
{   pulse_rate = rand_int(LO, HI);
}

void thermometer(int& temperature)
{   temperature = rand_int(LO, HI);
}

void blood_pressure(int& diastolic, int& systolic)
{   diastolic = rand_int(LO, HI);
    systolic = rand_int(LO, HI);   
}

void print_chart(string name,
int age, string ssn, int diastolic, int systolic,
int temperature, int pulse_rate)
{   cout << "Name " << " " << name << "\n" <<
            "Age " << " " << age << "\n" <<
            "SSN: " << " " << ssn << "\n" <<
            "Diastolic: " << " " << diastolic << "\n" <<
            "Systolic: " << " " << systolic << "\n" <<
            "Temperature: " << " " << temperature << "\n" <<
            "Pulse rate: " << " " << pulse_rate << "\n";
}


int main()
{  string name= "";
   int age = 0;
   string ssn = "";
   int diastolic = 0;
   int systolic = 0;
   int temperature = 0;
   int pulse_rate = 0;
   
   cout << "Name ? ";
   cin >> name;
   cout << "Age ? ";       
   cin >> age;
   cout << "SSN ? ";
   cin >> ssn;

   blood_pressure(diastolic, systolic);
   thermometer(temperature);
   pulse(pulse_rate);
   
   print_chart(name, age, ssn, diastolic, systolic, temperature, pulse_rate);
   return EXIT_SUCCESS;
}
/* PURPOSE: Draw a stick figure that waves its right arm
*/
#define CCC_WIN
#include "ccc.h"

int main()
{   Point upper_torso(0.0, 5.0);
    Point lower_torso(0.0, -3.0);
    Point lower_left_arm(0.0, 4.0);
    Point upper_left_arm(-4.0, 3.0);
    Point lower_right_arm(0.0, 4.0);
    Point upper_right_arm(4.0, 7.0);    
    Point upper_left_leg(0.0, -3.0);
    Point lower_left_leg(-5.0, -9.0);    
    Point upper_right_leg(0.0, -3.0);
    Point lower_right_leg(5.0, -9.0);        

/*  wave right arm  */
    while(true)                       
    {  upper_right_arm = Point(3.0, 8.0);
       cwin.clear();
       cwin << Circle(Point(0.0,6.0), 1.0)
            << Line(upper_torso, lower_torso)
                    << Line(upper_left_arm, lower_left_arm)
                    << Line(upper_right_arm, lower_right_arm)
            << Line(upper_left_leg, lower_left_leg)
                    << Line(upper_right_leg, lower_right_leg);
              
       upper_right_arm = Point(4.0, 7.0);
       cwin.clear();
           cwin << Circle(Point(0.0,6.0), 1.0)
            << Line(upper_torso, lower_torso)
                    << Line(upper_left_arm, lower_left_arm)
                    << Line(upper_right_arm, lower_right_arm)
            << Line(upper_left_leg, lower_left_leg)
                    << Line(upper_right_leg, lower_right_leg);
    }
        return EXIT_SUCCESS;
}    

R2. Interfaces

An object is constructed and it's data accessed and modified only through the use of a class' member functions. These functions define a 'black box' interface to the member data. Provide a constructor and the accessors and mutators necessary to perform the identified services from within a main function using the classes you defined in the of three preceeding examples.

Optimal Ticket Price

Patient Vital Sign Graph

Waving Stick Figure


R3. Encapsulation

Consider the following class declaration.

class Product
{
public:
   Product(string _name, double price);
   
   void increase_price(double percentage);
   int get_price() const;
   int quantity;
private:
   string name;
   double price;
}

class Product fails to effectively encapsulate a data member, thereby risking a runtime error due to corrupted data. Locate the problem(s) and propose a solution.

One of the data mambers is properly encapsulated but its value cannot be detected. What is it, and what member function might be added later that might use it?


P1. Member functions

Suppose that the Product class is going to be expanded for use in an inventory control system. Declare data fields, accessors and mutators which will keep track of the number of units of type Product that have been sold.

class Product
{
public:
   Product();
   Product(string _name, double price);
   
   void increase_price(double percentage);
   int get_price() const;

   void print() const;
   /*
      Your work goes here.
   */

private:
   string name;
   float price;
   int score;
   /*
      ... and here.
   */
}

Write a program that tests the features of your Product class.

Suppose that management now wants to automate the inventory control system. You'll need to declare or modify data members, constructors, accessors and mutators to expand the Product class to reorder more of itself when needed. Specifically, have every Product know its minimum supply, min_inventory, and the amount to order reorder_qty if the supply gets too low.

Enhance your Product class to fulfill the new requirements. Write a program that tests the new feature. Insert print statements into your code to provide a trace of your program's execution of a series of sales and a subsequent reorder.


P2. Object Construction

In each of the following examples, provide a constructor and a print function for the specified object.

/* PURPOSE: Prints out generic greeting from vacation spot of choice 
 */

Postcard::print() 
{   cout << "Dear " << "\n";
    cout << to_string << ",\n";
    cout << "Weather's great, Wish you were here !" << "\n";
    cout << "See you soon," << "\n";
    cout << from_string << ",\n";
}

Write a program that constructs a postcard object and calls the print member function.

class BankAccount
/* PURPOSE: Simulate opening an new account at Grand Cayman 
            Savings and Loan.
 */            
{  public:
      Account::Account(string new_name, double initial_balance);
               
      .
      .
      .
                     
   private:
                                     /* randomly assigned integer */   
      int    account_number;
                                     /* first, middle and last names
                                        extracted from input name */
      string last;
      string middle;
      string first;

      double balance;
}

Write a program that constructs an Account object and calls the print member function.


R4. Comparing non-member with member functions

Describe each of the parameters to the following functions as one of the four combinations of implicit/explicit and reference/value parameters as described in the text.

Parameter type Explicit parameter Implicit parameter
Reference parameter, can be updated Use & default behavior
Value parameter, cannot be updated default behavior const member function



float perimeter(Circle c)
float area(Circle c)
void Point::rotate(Point p, float angle)
void Message::get_start() const
void swap(int& a, int& b)
void Circle::move(int dx, int dy)
Point line::get_end() const

P3. Using object oriented design to build complex programs

The objects we've used are particular instances of generally defined classes. For example, Harry Hacker is a particular instance of the Employee class who happened to get a raise last year, whereas another employee might not have gotten one.

Classes in C++ can be thought of in terms of nouns and verbs, where a noun is something and a verb does something. Frequently, the noun is stored as data and the verbs are represented by member functions which access and mutate the data. It is also not unusual for classes to contain objects of other classes as data. Several classes can also be combined into a larger program to perform more complex tasks, for example, simulating a real world situation.

Earlier in this lab, you developed Account and Product classes. These are either suitable or extensible for use in many business transactions, for example a vending machine. Suppose now that you are running a company that supplies vending machines.

Your customers are other companies or organizations who place the machines on their premises. Your customers pay you a rental charge and buy the drinks from you at a wholesale price. They get to keep the money that their customers, that is, the users of the vending machines, pay for the drinks.

Once a week, a maintenance person comes along to restock the machine. At that time, the machine's account gets credited for the retail price of the purchased drinks and it gets debited for the weekly rental charge and the wholesale price of the restocked drinks.

In your program, you can choose to implement a graphical user interface and accept mouse clicks, or a text-based interface where you prompt the user what button to press. (You should assume that a user who buys a drink automatically inserts the correct change.) Also assume that the "Restock" button is only pressed by an authorized person (perhaps it is operated by a key).

Vending  Machine

Finding Interfaces

Supply the interfaces for VendingMachine, Product and Account classes to simulate this business situation.

Implementing Interfaces

Implement the interfaces you designed and combine them into a simulation program. Your program should simulate two machines.


Don't forget to send your answers when you're finished.