© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book C++ How to Program, 5th Edition, by Deitel and Deitel. ISBN 0-13-185757-6.
3 Introduction to Classes and Objects You will see something new. Two things. And I call them Thing One and Thing Two. —Dr. Theodor Seuss Geisel
Nothing can have value without being an object of utility.
In this chapter you will learn: ■
—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
■
■
■
■
■
■
■
What classes, objects, member functions and data members are. 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 mem ber function of an object to make that member function perform its task. The differences between data members of a class and local variables of a function. How to use a constructor to ensure that an object’s data is initialized when the object is created. How to engineer a class to separate its interface from its implementation and encourage reuse.
Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
76
Chapter 3
Introduction to Classes and Objects
Self-Review Exercises 3.1
Fill in the blanks in each of the following: a) A house is to a blueprint as a(n) is to a class. ANS : object. b) Every class definition contains keyword followed immediately by the class’s name. ANS : class. c) A class definition is typically stored in a file with the filename extension. ANS :
.h
d) Each parameter in a function header should specify both a(n) and a(n) . ANS : type, name. e) When each object of a class maintains its own copy of an attribute, the variable that represents the attribute is also known as a(n) . ANS : data member. f) Keyword public is a(n) . ANS : access specifier. g) Return type indicates that a function will perform a task but will not return any information when it completes its task. ANS : void. h) Function from the library reads characters until a newline character is encountered, then copies those characters into the specified string. ANS : getline. i) When a member function is defined outside the class definition, the function header must include the class name and the , followed by the function name to “tie” the member function to the class definition. ANS : binary scope resolution operator (::). j) The source-code file and any other files that use a class can include the class’s header file via an preprocessor directive. ANS : #include. 3.2
State whether each of the following is true or false . If false , explain why. a) By convention, function names begin with a capital letter and all subsequent words in the name begin with a capital letter. ANS : False. By convention, function names begin with a lowercase first letter and all subsequent words in the name begin with a capital first letter. b) Empty parentheses following a function name in a function prototype indicate that the function does not require any parameters to perform its task. ANS : True. c) Data members or member functions declared with access specifier private are accessible to member functions of the class in which they are declared. ANS : True. d) Variables declared in the body of a particular member function are known as data members and can be used in all member functions of the class. ANS : False. Such variables are called local variables and can be used only in the member function in which they are declared. e) Every function’s body is delimited by left and right braces ({ and }). ANS : True. f) Any source-code file that contains int main() can be used to execute a program. ANS : True. Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Exercises
77
g) The types of arguments in a function call must match the types of the corresponding parameters in the function prototype’s parameter list. ANS : True. 3.3
What is the difference between a local variable and a data member? ANS : A local variable is declared in the body of a function and can be used only from the point at which it is declared to the immediately following closing brace. A data member is declared in a class definition, but not in the body of any of the class’s member functions. Every object (instance) of a class has a separate copy of the class’s data members. Also, data members are accessible to all member functions of the class.
Explain the purpose of a function parameter. What is the difference between a parameter and an argument? ANS : A parameter represents additional information that a function requires to perform its task. Each parameter required by a function is specified in the function header. An argument is the value supplied in the function call. When the function is called, the argument value is passed into the function parameter so that the function can perform its task. 3.4
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 function so that the compiler can verify that programs call the function correctly. A function 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 function definition and optional in the function prototype.
What is a default constructor? How are an object’s data members initialized if a class has only an implicitly defined default constructor? ANS : A default constructor is the constructor that is called when a programmer creates an object without specifying any arguments to a constructor. The programmer can write a default constructor that initializes data members any way the programmer chooses. The compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor. The default constructor provided by the compiler creates an object without assigning any initial values to the object’s data members—data members must be initialized using the object’s member functions. Every constructor implicitly calls the constructors of any data member objects before the body of the class’s constructor executes. 3.6
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 represent the balance of the account. Each Account object maintains its own balance, but does not know the balances of the bank’s other accounts.
Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Chapter 3
78
Introduction to Classes and Objects
3.8
What is a header file? What is a source-code file? Discuss the purpose of each. ANS : A header file typically contains a class definition, in which the member functions and data members of the class are declared (function prototypes are function declarations). A source-code file is typically used to provide the definitions of the member functions declared in the class’s header file.
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 occurrence of the word string is prefixed by the namespace std and the binary scope resolution operator (::), as in std::string.
3.10
Explain why a class might provide a set function and a get function for a data member. ANS : A data member is typically declared private in a class so that only the member functions of the class in which the data member is declared can manipulate the variable. A class typically provides a set function and a get function for a data member to allow clients of the class to manipulate the data member in a control led manner. A set function should validate the data it is setting to ensure that invalid data is not placed in the object. A get function can return the value of a data member without allowing clients to interact with the data member directly. In addition, set and get functions hide the internal data representation. For example, a Time class might represent the time as the total number of seconds since midnight. Such a class can provide member functions getHour, getMinute and getSecond to calculate the hour, minute and second, respectively—even if the underlying data representation does not contain hour, minute and second data members. Similarly, a Time class could provide member functions setHour, setMinute and setSecond to set the current hour, minute or second value. This would require each set function to perform calculations that update the data member containing the total number of seconds since midnight.
3.11
(Modifying Class GradeBook ) Modify class GradeBook (Figs. 3.11–3.12) as follows: a) Include a second string data member that represents the course instructor’s name. b) Provide a set function to change the instructor’s name and a get function to retrieve it. c) Modify the constructor to specify two parameters—one for the course name and one for the instructor’s name. d) Modify member function displayMessage such that it first outputs the welcome message and course name, then outputs "This course is presented by: " followed by the instructor’s name.
Use your modified class in a test program that demonstrates the class’s new capabilities. ANS :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Exercise 3.11 Solution: GradeBook.h // Definition of GradeBook class that stores an instructor's name. #include // program uses C++ standard string class using std::string; // GradeBook class definition class GradeBook { public: // constructor initializes course name and instructor name GradeBook( string, string ); void setCourseName( string ); // function to set the course name string getCourseName(); // function to retrieve the course name void setInstructorName( string ); // function to set instructor name Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Exercises
79
15 16 17 18 19 20
string getInstructorName(); // function to retrieve instructor name void displayMessage(); // display welcome message and instructor name private: string courseName; // course name for this GradeBook string instructorName; // instructor name for this GradeBook }; // end class GradeBook
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
// Exercise 3.11 Solution: GradeBook.cpp // Member-function definitions for class GradeBook. #include using std::cout; using std::endl; // include definition of class GradeBook from GradeBook.h #include "GradeBook.h" // constructor initializes courseName and instructorName // with strings supplied as arguments GradeBook::GradeBook( string course, string instructor ) { setCourseName( course ); // initializes courseName setInstructorName( instructor ); // initialiZes instructorName } // end GradeBook constructor // function to set the course name void GradeBook::setCourseName( string name ) { courseName = name; // store the course name } // end function setCourseName // function to retrieve the course name string GradeBook::getCourseName() { return courseName; } // end function getCourseName // function to set the instructor name void GradeBook::setInstructorName( string name ) { instructorName = name; // store the instructor name } // end function setInstructorName // function to retrieve the instructor name string GradeBook::getInstructorName() { return instructorName; } // end function getInstructorName // display a welcome message and the instructor's name void GradeBook::displayMessage() { // display a welcome message containing the course name cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Chapter 3
80
48 49 50 51
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Introduction to Classes and Objects
// display the instructor's name cout << "This course is presented by: " << getInstructorName() << endl; } // end function displayMessage
// Exercise 3.11 Solution: ex03_11.cpp // Test program for modified GradeBook class. #include using std::cout; using std::endl; // include definition of class GradeBook from GradeBook.h #include "GradeBook.h" // function main begins program execution int main() { // create a GradeBook object; pass a course name and instructor name GradeBook gradeBook( "CS101 Introduction to C++ Programming", "Professor Smith" ); // display initial value of instructorName of GradeBook object cout << "gradeBook instructor name is: " << gradeBook.getInstructorNa me() << "\n\n";
// modify the instructorName using set function gradeBook.setInstructorName( "Assistant Professor Bates" ); // display new value of instructorName cout << "new gradeBook instructor name is: " << gradeBook.getInstructorNa me() << "\n\n";
// display welcome message and instructor's name gradeBook.displayMessage(); return 0; // indicate successful termination } // end main
gradeBook instructor name is: Professor Smith new gradeBook instructor name is: Assistant Professor Bates Welcome to the grade book for CS101 Introduction to C++ Programming! This course is presented by: Assistant Professor Bates
( Account Class) Create a class called Account that a bank might use to represent customers’ bank accounts. Your class should include one data member of type int to represent the account balance. [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 provide a constructor that receives an initial balance and uses it to initialize the data m ember. The constructor should validate the initial balance to ensure that it is greater than or equal to 0. If not, the balance should be set to 0 and the constructor should display an error message, indicating that the initial balance was 3.12
Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Exercises
81
invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and should ensure that the debit amount does not exceed the Account’s balance. If it does, the balance should be left unchanged and the function should print a message indicating "Debit amount exceeded account balance." Member function getBalance should return the current balance. Create a program that creates two Account objects and tests the member functions of class Account. ANS :
1 2 3 4 5 6 7 8 9 10 11 12 13
// Exercise 3.12 Solution: Account.h // Definition of Account class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// Exercise 3.12 Solution: Account.cpp // Member-function definitions for class Account. #include using std::cout; using std::endl;
class Account { public: Account( int ); // constructor initializes balance void credit( int ); // add an amount to the account balance void debit( int ); // subtract an amount from the account balance int getBalance(); // return the account balance private: int balance; // data member that stores the balance }; // end class Account
#include "Account.h" // include definition of class Account // Account constructor initializes data member balance Account::Account( int initialBalance ) { balance = 0; // assume that the balance begins at 0 // if initialBalance is greater than 0, set this value as the // balance of the Account; otherwise, balance remains 0 if ( initialBalance > 0 ) balance = initialBalance; // if initialBalance is negative, print error message if ( initialBalance < 0 ) cout << "Error: Initial balance cannot be negative.\n" << endl; } // end Account constructor // credit (add) an amount to the account balance void Account::credit( int amount ) { balance = balance + amount; // add amount to balance } // end function credit // debit (subtract) an amount from the account balance void Account::debit( int amount ) Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Chapter 3
82
Introduction to Classes and Objects
32 33 34 35 36 37 38 39 40 41 42 43 44
{
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
// Exercise 3.12 Solution: ex03_12.cpp // Create and manipulate Account objects. #include using std::cout; using std::cin; using std::endl;
if ( amount > balance ) // debit amount exceeds balance cout << "Debit amount exceeded account balance.\n" << endl; if ( amount <= balance ) // debit amount does not exceed balance balance = balance - amount; } // end function debit // return the account balance int Account::getBalance() { return balance; // gives the value of balance to the calling function } // end function getBalance
// include definition of class Account from Account.h #include "Account.h" // function main begins program execution int main() { Account account1( 50 ); // create Account object Account account2( 25 ); // create Account object // display initial balance of each object cout << "account1 balance: $" << account1.getBalance() << endl; cout << "account2 balance: $" << account2.getBalance() << endl; int withdrawalAmount; // stores withdrawal amount read from user cout << "\nEnter withdrawal amount for account1: "; // prompt cin >> withdrawalAmount; // obtain user input cout << "\nattempting to subtract " << withdrawalAmount << " from account1 balance\n\n"; account1.debit( withdrawalAmount ); // try to subtract from account1 // display balances cout << "account1 balance: $" << account1.getBalance() << endl; cout << "account2 balance: $" << account2.getBalance() << endl; cout << "\nEnter withdrawal amount for account2: "; // prompt cin >> withdrawalAmount; // obtain user input cout << "\nattempting to subtract " << withdrawalAmount << " from account2 balance\n\n"; account2.debit( withdrawalAmount ); // try to subtract from account2 // display balances cout << "account1 balance: $" << account1.getBalance() << endl; Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Exercises
41 42 43
83
cout << "account2 balance: $" << account2.getBalance() << endl; return 0; // indicate successful termination } // end main
account1 balance: $50 account2 balance: $25 Enter withdrawal amount for account1:
35
attempting to subtract 35 from account1 balance account1 balance: $15 account2 balance: $25 Enter withdrawal amount for account2:
50
attempting to subtract 50 from account2 balance Debit amount exceeded account balance. account1 balance: $15 account2 balance: $25
( 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 pieces of information as data members—a part number (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 calculates 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. 3.13
ANS :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Exercise 3.13 Solution: Invoice.h // Definition of Invoice class that represents an invoice // for an item sold at a hardware store. #include // program uses C++ standard string class using std::string; // Invoice class definition class Invoice { public: // constructor initializes the four data members Invoice( string, string, int, int ); // set and get functions for the four data members void setPartNumber( string ); // part number string getPartNumber(); void setPartDescription( string ); // part description Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
84
18 19 20 21 22 23 24 25 26 27 28 29 30 31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
Chapter 3
Introduction to Classes and Objects
string getPartDescription(); void setQuantity( int ); // quantity int getQuantity(); void setPricePerItem( int ); // price per item int getPricePerItem(); // calculates invoice amount by multiplying quantity x price per item int getInvoiceAmount(); private: string partNumber; // the number of the part being sold string partDescription; // description of the part being sold int quantity; // how many of the items are being sold int pricePerItem; // price per item }; // end class Invoice
// Exercise 3.13 Solution: Invoice.cpp // Member-function definitions for class Invoice. #include using std::cout; using std::endl; // include definition of class Invoice from Invoice.h #include "Invoice.h" // Invoice constructor initializes the class's four data members Invoice::Invoice( string number, string description, int count, int price ) { setPartNumber( number ); // store partNumber setPartDescription( description ); // store partDescription setQuantity( count ); // validate and store quantity setPricePerItem( price ); // validate and store pricePerItem } // end Invoice constructor // set part number void Invoice::setPartNumber( string number ) { partNumber = number; // no validation needed } // end function setPartNumber // get part number string Invoice::getPartNumber() { return partNumber; } // end function getPartNumber // set part description void Invoice::setPartDescription( string description ) { partDescription = description; // no validation needed } // end function setPartDescription // get part description string Invoice::getPartDescription() Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Exercises
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
1 2 3 4 5
{ return partDescription; } // end function getPartDescription // set quantity; if not positive, set to 0 void Invoice::setQuantity( int count ) { if ( count > 0 ) // if quantity is positive quantity = count; // set quantity to count if ( count <= 0 ) // if quantity is not positive { quantity = 0; // set quantity to 0 cout << "\nquantity cannot be negative. quantity set to 0.\n"; } // end if } // end function setQuantity // get quantity int Invoice::getQuantity() { return quantity; } // end function getQuantity // set price per item; if not positive, set to 0.0 void Invoice::setPricePerItem( int price ) { if ( price > 0 ) // if price is positive pricePerItem = price; // set pricePerItem to price if ( price <= 0 ) // if price is not positive { pricePerItem = 0; // set pricePerItem to 0 cout << "\npricePerItem cannot be negative. " << "pricePerItem set to 0.\n"; } // end if } // end function setPricePerItem // get price per item int Invoice::getPricePerItem() { return pricePerItem; } // end function getPricePerItem // calulates invoice amount by multiplying quantity x price per item int Invoice::getInvoiceAmount() { return getQuantity() * getPricePerItem(); } // end function getInvoiceAmount
// Exercise 3.13 Solution: ex03_13.cpp // Create and manipulate an Invoice object. #include using std::cout; using std::cin; Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
85
Chapter 3
86
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
Introduction to Classes and Objects
using std::endl; // include definition of class Invoice from Invoice.h #include "Invoice.h" // function main begins program execution int main() { // create an Invoice object Invoice invoice( "12345", "Hammer", 100, 5 ); // display the invoice data members and calculate the amount cout << "Part number: " << invoice.getPartNumber() << endl; cout << "Part description: " << invoice.getPartDescription() << endl; cout << "Quantity: " << invoice.getQuantity() << endl; cout << "Price per item: $" << invoice.getPricePerItem() << endl; cout << "Invoice amount: $" << invoice.getInvoiceAmount() << endl;
// modify the invoice data members invoice.setPartNumber( "123456" ); invoice.setPartDescription( "Saw" ); invoice.setQuantity( -5 ); // negative quantity, so quantity set to 0 invoice.setPricePerItem( 10 ); cout << "\nInvoice data members modified.\n\n";
// display the modified invoice data members and calculate new amount cout << "Part number: " << invoice.getPartNumber() << endl; cout << "Part description: " << invoice.getPartDescription() << endl; cout << "Quantity: " << invoice.getQuantity() << endl; cout << "Price per item: $" << invoice.getPricePerItem() << endl; cout << "Invoice amount: $" << invoice.getInvoiceAmount() << endl; return 0; // indicate successful termination } // end main
Part number: 12345 Part description: Hammer Quantity: 100 Price per item: $5 Invoice amount: $500 quantity cannot be negative. quantity set to 0. Invoice data members modified. Part number: 123456 Part description: Saw Quantity: 0 Price per item: $10 Invoice amount: $0
( Employee Class) Create a class called Employee that includes three pieces of information as data members—a first name (type string), a last name (type string) and a monthly salary (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 3.14
Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Exercises
87
initializes the three data members. Provide a set and a get function for each data member. If the monthly salary is not positive, set it to 0. Write a test program that demonstrates class Employee’s capabilities. Create two Employee objects and display each object’s yearly salary. Then give each Employee a 10 percent raise and display each Employee’s yearly salary again. ANS : [Note: The following solution may generate warnings because a double value is being passed as an int on lines 30–31 of the file ex03_14.cpp. The application still works correctly (as the monthly salary is supposed to be an integer), but you may want to mention the warnings to your students.] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Exercise 3.14 Solution: Employee.h // Employee class definition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Exercise 3.14 Solution: Employee.cpp // Employee class member-function definitions. #include using std::cout;
#include // program uses C++ standard string class using std::string; // Employee class definition class Employee { public: Employee( string, string, int ); // constructor sets data members void setFirstName( string ); // set first name string getFirstName(); // return first name void setLastName( string ); // set last name string getLastName(); // return last name void setMonthlySalary( int ); // set weekly salary int getMonthlySalary(); // return weekly salary private: string firstName; // Employee's first name string lastName; // Employee's last name int monthlySalary; // Employee's salary per month }; // end class Employee
#include "Employee.h" // Employee class definition // Employee constructor initializes the three data members Employee::Employee( string first, string last, int salary ) { setFirstName( first ); // store first name setLastName( last ); // store last name setMonthlySalary( salary ); // validate and store monthly salary } // end Employee constructor // set first name void Employee::setFirstName( string name ) { firstName = name; // no validation needed } // end function setFirstName
Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
88
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Chapter 3
Introduction to Classes and Objects
// return first name string Employee::getFirstName() { return firstName; } // end function getFirstName // set last name void Employee::setLastName( string name ) { lastName = name; // no validation needed } // end function setLastName // return last name string Employee::getLastName() { return lastName; } // end function getLastName // set monthly salary; if not positive, set to 0.0 void Employee::setMonthlySalary( int salary ) { if ( salary > 0 ) // if salary is positive monthlySalary = salary; // set monthlySalary to salary if ( salary <= 0 ) // if salary is not positive monthlySalary = 0; // set monthlySalary to 0.0 } // end function setMonthlySalary // return monthly salary int Employee::getMonthlySalary() { return monthlySalary; } // end function getMonthlySalary
// Exercise 3.14 Solution: ex03_14.cpp // Create and manipulate two Employee objects. #include using std::cout; using std::endl; #include "Employee.h" // include definition of class Employee // function main begins program execution int main() { // create two Employee objects Employee employee1( "Lisa", "Roberts", 4500 ); Employee employee2( "Mark", "Stein", 4000 ); // display each Employee's yearly salary cout << "Employees' yearly salaries: " << endl; // retrieve and display employee1's monthly salary multiplied by 12 Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Exercises
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
89
int monthlySalary1 = employee1.getMonthlySalary(); cout << employee1.getFirstName( ) << " " << employee1.getLastName() << ": $" << monthlySalary1 * 12 << endl; // retrieve and display employee2's monthly salary multiplied by 12 int monthlySalary2 = employee2.getMonthlySalary(); cout << employee2.getFirstName( ) << " " << employee2.getLastName() << ": $" << monthlySalary2 * 12 << endl; // give each Employee a 10% raise employee1.setMonthlySalar y( monthlySalary1 * 1.1 ); employee2.setMonthlySalar y( monthlySalary2 * 1.1 ); // display each Employee's yearly salary again cout << "\nEmployees' yearly salaries after 10% raise: " << endl; // retrieve and display employee1's monthly salary multiplied by 12 monthlySalary1 = employee1.getMonthlySalary(); cout << employee1.getFirstName( ) << " " << employee1.getLastName() << ": $" << monthlySalary1 * 12 << endl; monthlySalary2 = employee2.getMonthlySalary(); cout << employee2.getFirstName( ) << " " << employee2.getLastName() << ": $" << monthlySalary2 * 12 << endl; return 0; // indicate successful termination } // end main
Employees' yearly salaries: Lisa Roberts: $54000 Mark Stein: $48000 Employees' yearly salaries after 10% raise: Lisa Roberts: $59400 Mark Stein: $52800
( 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 constructor 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 is not, set the month to 1. Provide a set and a get function 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 capabilities. 3.15
ANS :
1 2 3 4 5 6 7 8 9
// Exercise 3.15 Solution: Date.h // Definition of class Date. // class Date definition class Date { public: Date( int, int, int ); // constructor initializes data members void setMonth( int ); // set month Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
90
Chapter 3
Introduction to Classes and Objects
10 11 12 13 14 15 16 17 18 19 20
int getMonth(); // return month void setDay( int ); // set day int getDay(); // return day void setYear( int ); // set year int getYear(); // return year void displayDate(); // displays date in mm/dd/yyyy format private: int month; // the month of the date int day; // the day of the date int year; // the year of the date }; // end class Date
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
// Exercise 3.15 Solution: Date.cpp // Member-function definitions for class Date. #include using std::cout; using std::endl; #include "Date.h" // include definition of class Date from Date.h // Date constructor that initializes the three data members; // assume values provided are correct (really should validate) Date::Date( int m, int d, int y ) { setMonth( m ); setDay( d ); setYear( y ); } // end Date constructor // set month void Date::setMonth( int m ) { month = m; if ( month < 1 ) month = 1; if ( month > 12 ) month = 1; } // end function setMonth // return month int Date::getMonth() { return month; } // end function getMonth // set day void Date::setDay( int d ) { day = d; } // end function setDay // return day Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
Exercises
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
int Date::getDay() { return day; } // end function getDay
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Exercise 3.15 Solution: ex03_15.cpp // Demonstrates class Date's capabilities. #include using std::cout; using std::endl;
// set year void Date::setYear( int y ) { year = y; } // end function setYear // return year int Date::getYear() { return year; } // end function getYear // print Date in the format mm/dd/yyyy void Date::displayDate() { cout << month << '/' << day << '/' << year << endl; } // end function displayDate
#include "Date.h" // include definition of class Date from Date.h // function main begins program execution int main() { Date date( 5, 6, 1981 ); // create a Date object for May 6, 1981 // display the values of the three Date data members cout << "Month: " << date.getMonth() << endl; cout << "Day: " << date.getDay() << endl; cout << "Year: " << date.getYear() << endl;
cout << "\nOriginal date:" << endl; date.displayDate(); // output the Date as 5/6/1981
// modify the Date date.setMonth( 13 ); // invalid month date.setDay( 1 ); date.setYear( 2005 );
cout << "\nNew date:" << endl; date.displayDate(); // output the modified date (1/1/2005) return 0; // indicate successful termination } // end main
Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved
91
92
Chapter 3
Introduction to Classes and Objects
Month: 5 Day: 6 Year: 1981 Original date: 5/6/1981 New date: 1/1/2005
Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved