Computing Concepts with C++ Essentials, 3rd ed.
Laboratory Notebook
Chapter 6 - Classes

John P. Russo
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    : best_profit.cpp
   PURPOSE : Calculates the best city for making a profit as a housing
			 contractor.	
*/

#include <iostream>
#include <string>
using namespace std;
             
int main()
{
   bool mdata = true;
   string response = "";
   double avg_sale_price = 0.0;
   double avg_building_cost = 0.0;
   double avg_profit = 0.0;
   double best_profit = 0.0;
   string city = "";
   string best_city = "";   
   
   while (mdata)
   {  cout << "Average building cost: ";
      cin >> avg_building_cost;
   
      cout << "Average sale price: ";
      cin >> avg_sale_price;

      cout << "City : ";
      cin >> city;
	  avg_profit = avg_sale_price - avg_building_cost;

      if ( avg_profit> best_profit)
      {   best_profit = avg_profit;
          best_city = city;
      }
  
      cout << "More data (y/n)? ";
      cin >> response;
      if (response != "y") 
      {   mdata = false;
      }
   }

   cout << "The best city to be a builder in is: "<<city << "\n";
   return 0;
}

/*  NAME:    perk_tst.cpp
    PURPOSE: Main program to record information about a properties perk test
*/

#include <iostream>
#include <string>
#include "rand.h"
using namespace std;
             
const int lower_limit = 7; 
const int upper_limit = 120;
const int lower_acceptable = 10;
const int upper_acceptable = 105;

void perc_dimension(int& width, int& length)
{   
	width = rand_int(1,20);
	length = rand_int(1,20);
}

void air_temp(int& temperature)
{   
	temperature = rand_int(0,120);
}

void perc_rate(int& prate)
{ 
	prate = rand_int(lower_limit,upper_limit);
}

void print_report(string site,string city, int length, int width,int prate,int temperature)
{   
	cout << "Site        " << " " << site << "\n" <<
            "City        " << " " << city << "\n" <<
            "Dimensions  " << " " << length <<" X "<<width<< "\n" <<
            "Air Temp    " << " " << temperature<< "\n" <<
			"Perc Rate   " << " " << prate <<"\n";
	if (prate >= lower_acceptable && prate <= upper_acceptable)
		cout <<"Perc test is ok!\n";
	else
		cout <<"Perc test is not ok!\n";

}


int main()
{ 
   string site = "";
   string city = "";
   int temperature = 0;
   int width = 0;
   int length = 0;
   int percrate = 0;
   
   cout << "Site ? ";
   cin >> site;
   cout << "City ? ";       
   cin >> city;
   rand_seed();
   perc_dimension(width,length);
   air_temp(temperature);
   perc_rate(percrate);
   print_report(site,city,length,width,percrate,temperature);
   return 0;
}

/* PURPOSE: Draw a stick figure that waves its right arm
*/
#include "ccc_win.cpp"

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 0;
}    


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.

best_profit

Perc Test

Waving Stick Figure


R3. Encapsulation

Consider the following class declaration.

class Customer
{
public:
   Customer(string name, string address, string city, string state, string zipcode);
   
   void increase_limit(double amount);
   string get_name()  const;
   string get_address() const;
   string get_city()  const;
   string get_state() const;
   double credit_limit;
private:
   string name;
   string address;
   string city;
   string state;
   string zipcode;
}

class Customer 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 members 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 Customer class is going to be expanded to keep track of  total year-to-date purchases.Declare data fields, accessors and mutators which will keep track of the total number of sales and total sales for each instance of Customer.

class Customer
{
public:
   Customer(string name, string address, string city, string state, string zipcode);
   
   void increase_limit(double amount);
   string get_name()  const;
   string get_address() const;
   string get_city()  const;
   string get_state() const;
   double credit_limit;
   /*your work goes here
   */
private:
   string name;
   string address;
   string city;
   string state;
   string zipcode;
   /* and here
   */
  ;
}

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

Suppose that management now wants to automate the customer management system to detect when a new purchase cannot be made because the credit limit will be exceeded.  You'll need to declare or modify data members, constructors, accessors and mutators to expand the Customer class to return a value specifying that a new purchase would exceed the credit limit. This can be calculated by passing the purchase price into a member function, adding this to the unpaid balance and comparing it to the credit line.

Enhance your Customer 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


double perimeter(Circle c)

double area(Circle c)

void Point::rotate(Point p, double 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 class to perform more complex tasks, for example, simulating a real world situation.

Earlier in this lab, you developed Account and Customer classes. These are either suitable or extensible for use in many business transactions, for example a Point-of-Sale Terminal. Suppose now that you are running a company that sells clothing and automatically debits from a banking account once the customer's balance reaches a predefined amount.  Your program should, either through a graphical user interface or character based interface, ask the user for the name of the item purchased, the quantity, the purchase price and the name of the customer.  It should then check to make sure that the customer has adequate credit available.  If the customer does, then the purchase should be added to the unpaid balance.  If the customer does not have an adequate balance, then the unpaid balance should be debited from the customer's checking account.  This will bring the unpaid balance down to zero.  Also, there should be a trigger point at which the unpaid balance gets debited (say $1000). 

Finding Interfaces

Supply the interfaces for POS, Customer 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 POS terminals.


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