Chapter 3
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
787
On Slideshare
787
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
16
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Introduction to Classes andObjects: Solutions 3 Nothing can have value without being an object of utility. —Karl Marx Your public servants serve you right. —Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message. —Amenemope Objectives In this chapter you’ll learn: ■ How to define a class and use it to create an object. ■ How to define member functions in a class to implement the class’s behaviors. ■ How to declare data members in a class to implement the class’s attributes. ■ How to call a member function of an object to perform a task. ■ The differences between data members of a class and local variables of a function. ■ How to use a constructor to initialize an object’s data when the object is created. ■ How to engineer a class to separate its interface from its implementation and encourage reuse. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 2. 2 Chapter 3 Introduction to Classes and Objects: Solutions Student Solution Exercises 3.5 Explain the difference between a function prototype and a function definition. ANS: A function prototype tells the compiler the name of a function and the type of data returned by the function. A prototype also describes any additional data required by the function to perform its task (i.e., the function’s parameters). A prototype does not contain code to make the function perform the task—it merely "outlines" the func- tion so that the compiler can verify that programs call the function correctly. A func- tion definition contains the actual code that executes to perform the function’s specified task when the function is called. Parameter names are required in the func- tion definition and optional in the function prototype. 3.7 Explain the purpose of a data member. ANS: A class provides a data member (or several data members) when each object of the class must maintain data separately from all other objects of the class. For example, a class called Account that represents a bank account provides a data member to repre- sent the balance of the account. Each Account object maintains its own balance but does not know the balances of the bank’s other accounts. 3.9 Explain how a program could use class string without inserting a using declaration. ANS: A program could create string variables without a using declaration if each occur- rence of the word string were prefixed by the namespace std and the binary scope resolution operator (::), as in std::string. 3.13 (Invoice Class) Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four data members—a part num- ber (type string), a part description (type string), a quantity of the item being purchased (type int) and a price per item (type int). [Note: In subsequent chapters, we’ll use numbers that contain decimal points (e.g., 2.75)—called floating-point values—to represent dollar amounts.] Your class should have a constructor that initializes the four data members. Provide a set and a get function for each data member. In addition, provide a member function named getInvoiceAmount that calcu- lates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount as an int value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0. Write a test program that demonstrates class Invoice’s capabilities. ANS: 1 // Exercise 3.13 Solution: Invoice.h 2 // Definition of Invoice class that represents an invoice 3 // for an item sold at a hardware store. 4 #include <string> // program uses C++ standard string class 5 using namespace std; 6 7 // Invoice class definition 8 class Invoice 9 {10 public:11 // constructor initializes the four data members12 Invoice( string, string, int, int );1314 // set and get functions for the four data members15 void setPartNumber( string ); // part number16 string getPartNumber();17 void setPartDescription( string ); // part description © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 3. Student Solution Exercises 318 string getPartDescription();19 void setQuantity( int ); // quantity20 int getQuantity();21 void setPricePerItem( int ); // price per item22 int getPricePerItem();2324 // calculates invoice amount by multiplying quantity x price per item25 int getInvoiceAmount();26 private:27 string partNumber; // the number of the part being sold28 string partDescription; // description of the part being sold29 int quantity; // how many of the items are being sold30 int pricePerItem; // price per item31 }; // end class Invoice 1 // Exercise 3.13 Solution: Invoice.cpp 2 // Member-function definitions for class Invoice. 3 #include <iostream> 4 #include "Invoice.h" 5 using namespace std; 6 7 // Invoice constructor initializes the classs four data members 8 Invoice::Invoice( string number, string description, int count, 9 int price )10 {11 setPartNumber( number ); // store partNumber12 setPartDescription( description ); // store partDescription13 setQuantity( count ); // validate and store quantity14 setPricePerItem( price ); // validate and store pricePerItem15 } // end Invoice constructor1617 // set part number18 void Invoice::setPartNumber( string number )19 {20 partNumber = number; // no validation needed21 } // end function setPartNumber2223 // get part number24 string Invoice::getPartNumber()25 {26 return partNumber;27 } // end function getPartNumber2829 // set part description30 void Invoice::setPartDescription( string description )31 {32 partDescription = description; // no validation needed33 } // end function setPartDescription3435 // get part description36 string Invoice::getPartDescription()37 {38 return partDescription; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 4. 4 Chapter 3 Introduction to Classes and Objects: Solutions39 } // end function getPartDescription4041 // set quantity; if not positive, set to 042 void Invoice::setQuantity( int count )43 {44 if ( count > 0 ) // if quantity is positive45 quantity = count; // set quantity to count4647 if ( count <= 0 ) // if quantity is not positive48 {49 quantity = 0; // set quantity to 050 cout << "nquantity cannot be negative. quantity set to 0.n";51 } // end if52 } // end function setQuantity5354 // get quantity55 int Invoice::getQuantity()56 {57 return quantity;58 } // end function getQuantity5960 // set price per item; if not positive, set to 0.061 void Invoice::setPricePerItem( int price )62 {63 if ( price > 0 ) // if price is positive64 pricePerItem = price; // set pricePerItem to price6566 if ( price <= 0 ) // if price is not positive67 {68 pricePerItem = 0; // set pricePerItem to 069 cout << "npricePerItem cannot be negative. "70 << "pricePerItem set to 0.n";71 } // end if72 } // end function setPricePerItem7374 // get price per item75 int Invoice::getPricePerItem()76 {77 return pricePerItem;78 } // end function getPricePerItem7980 // calulates invoice amount by multiplying quantity x price per item81 int Invoice::getInvoiceAmount()82 {83 return getQuantity() * getPricePerItem();84 } // end function getInvoiceAmount1 // Exercise 3.13 Solution: ex03_13.cpp2 // Create and manipulate an Invoice object.3 #include <iostream>4 #include "Invoice.h"5 using namespace std;6 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 5. Student Solution Exercises 5 7 // function main begins program execution 8 int main() 9 {10 // create an Invoice object11 Invoice invoice( "12345", "Hammer", 100, 5 );1213 // display the invoice data members and calculate the amount14 cout << "Part number: " << invoice.getPartNumber() << endl;15 cout << "Part description: " << invoice.getPartDescription() << endl;16 cout << "Quantity: " << invoice.getQuantity() << endl;17 cout << "Price per item: $" << invoice.getPricePerItem() << endl;18 cout << "Invoice amount: $" << invoice.getInvoiceAmount() << endl;1920 // modify the invoice data members21 invoice.setPartNumber( "123456" );22 invoice.setPartDescription( "Saw" );23 invoice.setQuantity( -5 ); // negative quantity, so quantity set to 024 invoice.setPricePerItem( 10 );25 cout << "nInvoice data members modified.nn";2627 // display the modified invoice data members and calculate new amount28 cout << "Part number: " << invoice.getPartNumber() << endl;29 cout << "Part description: " << invoice.getPartDescription() << endl;30 cout << "Quantity: " << invoice.getQuantity() << endl;31 cout << "Price per item: $" << invoice.getPricePerItem() << endl;32 cout << "Invoice amount: $" << invoice.getInvoiceAmount() << endl;33 return 0; // indicate successful termination34 } // end mainPart number: 12345Part description: HammerQuantity: 100Price per item: $5Invoice amount: $500quantity cannot be negative. quantity set to 0.Invoice data members modified.Part number: 123456Part description: SawQuantity: 0Price per item: $10Invoice amount: $0 3.15 (Date Class) Create a class called Date that includes three pieces of information as data members—a month (type int), a day (type int) and a year (type int). Your class should have a con- structor with three parameters that uses the parameters to initialize the three data members. For the purpose of this exercise, assume that the values provided for the year and day are correct, but ensure that the month value is in the range 1–12; if it isn’t, set the month to 1. Provide a set and a get func- tion for each data member. Provide a member function displayDate that displays the month, day and year separated by forward slashes (/). Write a test program that demonstrates class Date’s capa- bilities. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 6. 6 Chapter 3 Introduction to Classes and Objects: Solutions ANS: 1 // Exercise 3.15 Solution: Date.h 2 // Definition of class Date. 3 4 // class Date definition 5 class Date 6 { 7 public: 8 Date( int, int, int ); // constructor initializes data members 9 void setMonth( int ); // set month10 int getMonth(); // return month11 void setDay( int ); // set day12 int getDay(); // return day13 void setYear( int ); // set year14 int getYear(); // return year15 void displayDate(); // displays date in mm/dd/yyyy format16 private:17 int month; // the month of the date18 int day; // the day of the date19 int year; // the year of the date20 }; // end class Date 1 // Exercise 3.15 Solution: Date.cpp 2 // Member-function definitions for class Date. 3 #include <iostream> 4 #include "Date.h" // include definition of class Date from Date.h 5 using namespace std; 6 7 // Date constructor that initializes the three data members; 8 // assume values provided are correct (really should validate) 9 Date::Date( int m, int d, int y )10 {11 setMonth( m );12 setDay( d );13 setYear( y );14 } // end Date constructor1516 // set month17 void Date::setMonth( int m )18 {19 month = m;2021 if ( month < 1 )22 month = 1;2324 if ( month > 12 )25 month = 1;26 } // end function setMonth2728 // return month29 int Date::getMonth()30 { © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 7. Student Solution Exercises 731 return month;32 } // end function getMonth3334 // set day35 void Date::setDay( int d )36 {37 day = d;38 } // end function setDay3940 // return day41 int Date::getDay()42 {43 return day;44 } // end function getDay4546 // set year47 void Date::setYear( int y )48 {49 year = y;50 } // end function setYear5152 // return year53 int Date::getYear()54 {55 return year;56 } // end function getYear5758 // print Date in the format mm/dd/yyyy59 void Date::displayDate()60 {61 cout << month << / << day << / << year << endl;62 } // end function displayDate 1 // Exercise 3.15 Solution: ex03_15.cpp 2 // Demonstrates class Dates capabilities. 3 #include <iostream> 4 #include "Date.h" // include definition of class Date from Date.h 5 using namespace std; 6 7 // function main begins program execution 8 int main() 9 {10 Date date( 5, 6, 1981 ); // create a Date object for May 6, 19811112 // display the values of the three Date data members13 cout << "Month: " << date.getMonth() << endl;14 cout << "Day: " << date.getDay() << endl;15 cout << "Year: " << date.getYear() << endl;1617 cout << "nOriginal date:" << endl;18 date.displayDate(); // output the Date as 5/6/19811920 // modify the Date © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 8. 8 Chapter 3 Introduction to Classes and Objects: Solutions21 date.setMonth( 13 ); // invalid month22 date.setDay( 1 );23 date.setYear( 2005 );2425 cout << "nNew date:" << endl;26 date.displayDate(); // output the modified date (1/1/2005)27 return 0; // indicate successful termination28 } // end mainMonth: 5Day: 6Year: 1981Original date:5/6/1981New date:1/1/2005 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.