You are on page 1of 18

3

You will see something new.


Two things. And I call them
Thing One and Thing Two.

Introduction to
Classes and
Objects

Dr. Theodor Seuss Geisel

Nothing can have value


without being an object of
utility.

OBJECTIVES
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

What classes, objects, member functions and data


members are.
How to dene a class and use it to create an object.
How to dene member functions in a class to implement
the classs behaviors.
How to declare data members in a class to implement the
classs attributes.
How to call a member 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 objects data
is initialized when the object is created.
How to engineer a class to separate its interface from its
implementation and encourage reuse.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

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)
ANS: object.
b) Every class definition contains keyword
classs name.

ANS: class.

is to a class.

c) A class definition is typically stored in a file with the

followed immediately by 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 <string> 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 classs 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 functions 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.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

g) The types of arguments in a function call must match the types of the corresponding
parameters in the function prototypes 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 classs member
functions. Every object (instance) of a class has a separate copy of the classs data
members. Also, data members are accessible to all member functions of the class.

3.4
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.

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 functions parameters). A prototype does not
contain code to make the function perform the taskit 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 functions specified
task when the function is called. Parameter names are required in the function definition and optional in the function prototype.

3.6
What is a default constructor? How are an objects 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 objects data membersdata members must be initialized using the objects member functions. Every
constructor implicitly calls the constructors of any data member objects before the
body of the classs constructor executes.
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 banks other accounts.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 3 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 classs 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 controlled 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, respectivelyeven 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.113.12) as follows:


a) Include a second string data member that represents the course instructors name.
b) Provide a set function to change the instructors name and a get function to retrieve it.
c) Modify the constructor to specify two parametersone for the course name and one
for the instructors 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
instructors name.
Use your modied class in a test program that demonstrates the classs new capabilities.
ANS:

1
2
3
4
5
6
7
8
9
10
11
12
13

// Exercise 3.11 Solution: GradeBook.h


// Definition of GradeBook class that stores an instructor's name.
#include <string> // 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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

14
15
16
17
18
19
20

void setInstructorName( string ); // function to set instructor name


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

// Exercise 3.11 Solution: GradeBook.cpp


// Member-function definitions for class GradeBook.
#include <iostream>
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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

6
46
47
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

Chapter 3 Introduction to Classes and Objects

cout << "Welcome to the grade book for\n" << getCourseName() << "!"
<< endl;
// 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 <iostream>
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.getInstructorName() << "\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.getInstructorName() << "\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

3.12 (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, well use numbers that contain decimal points (e.g., 2.75)
called floating-point valuesto represent dollar amounts.] Your class should provide a constructor
that receives an initial balance and uses it to initialize the data member. The constructor should val 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

idate 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
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 Accounts 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

// Exercise 3.12 Solution: Account.cpp


// Member-function definitions for class Account.
#include <iostream>
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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

8
29
30
31
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

Chapter 3 Introduction to Classes and Objects

// debit (subtract) an amount from the account balance


void Account::debit( int amount )
{
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

// Exercise 3.12 Solution: ex03_12.cpp


// Create and manipulate Account objects.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// 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";

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
37
38
39
40
41
42
43

account2.debit( withdrawalAmount ); // try to subtract from account2


// display balances
cout << "account1 balance: $" << account1.getBalance() << endl;
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

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 pieces of information as
data membersa 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, well
use numbers that contain decimal points (e.g., 2.75)called floating-point valuesto 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 Invoices capabilities.
ANS:

1
2
3
4
5
6
7
8
9
10
11
12

// Exercise 3.13 Solution: Invoice.h


// Definition of Invoice class that represents an invoice
// for an item sold at a hardware store.
#include <string> // 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 );

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

10
13
14
15
16
17
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

Chapter 3 Introduction to Classes and Objects

// set and get functions for the four


void setPartNumber( string ); // part
string getPartNumber();
void setPartDescription( string ); //
string getPartDescription();
void setQuantity( int ); // quantity
int getQuantity();
void setPricePerItem( int ); // price
int getPricePerItem();

data members
number
part description

per item

// 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 <iostream>
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 )

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
34
35
36
37
38
39
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

partDescription = description; // no validation needed


} // end function setPartDescription
// get part description
string Invoice::getPartDescription()
{
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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

11

12
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

Chapter 3 Introduction to Classes and Objects

// Exercise 3.13 Solution: ex03_13.cpp


// Create and manipulate an Invoice object.
#include <iostream>
using std::cout;
using std::cin;
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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

13

3.14 (Employee Class) Create a class called Employee that includes three pieces of information as
data membersa first name (type string), a last name (type string) and a monthly salary (type
int). [Note: In subsequent chapters, well use numbers that contain decimal points (e.g., 2.75)
called floating-point valuesto represent dollar amounts.] Your class should have a constructor that
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 Employees
capabilities. Create two Employee objects and display each objects yearly salary. Then give each Employee a 10 percent raise and display each Employees yearly salary again.
ANS: [Note: The following solution may generate warnings because a double value is being
passed as an int on lines 3031 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

// Exercise 3.14 Solution: Employee.cpp


// Employee class member-function definitions.
#include <iostream>
using std::cout;

#include <string> // 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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

14

Chapter 3 Introduction to Classes and Objects

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
48
49
50
51
52
53
54

// set first name


void Employee::setFirstName( string name )
{
firstName = name; // no validation needed
} // end function setFirstName

1
2
3
4
5
6
7
8
9
10
11
12
13

// Exercise 3.14 Solution: ex03_14.cpp


// Create and manipulate two Employee objects.
#include <iostream>
using std::cout;
using std::endl;

// 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

#include "Employee.h" // include definition of class Employee


// function main begins program execution
int main()
{
// create two Employee objects
Employee employee1( "Lisa", "Roberts", 4500 );

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
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

15

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
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.setMonthlySalary( monthlySalary1 * 1.1 );
employee2.setMonthlySalary( 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

3.15 (Date Class) Create a class called Date that includes three pieces of information as data membersa 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 112; 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 Dates capabilities.
ANS:

1
2

// Exercise 3.15 Solution: Date.h


// Definition of class Date.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

16
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

Chapter 3 Introduction to Classes and Objects

// class Date definition


class Date
{
public:
Date( int, int, int ); // constructor initializes data members
void setMonth( int ); // set month
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

// Exercise 3.15 Solution: Date.cpp


// Member-function definitions for class Date.
#include <iostream>
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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
35
36
37
38
39
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

// set day
void Date::setDay( int d )
{
day = d;
} // end function setDay
// return day
int Date::getDay()
{
return day;
} // end function getDay
// 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

// Exercise 3.15 Solution: ex03_15.cpp


// Demonstrates class Date's capabilities.
#include <iostream>
using std::cout;
using std::endl;
#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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

17

18
23
24
25
26
27
28
29
30

Chapter 3 Introduction to Classes and Objects

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

Month: 5
Day: 6
Year: 1981
Original date:
5/6/1981
New date:
1/1/2005

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.