Programming
Programming
To the Distance class in the ENGLPLUS program in this chapter, add an overloaded
//- operator that subtracts two distances. It should allow statements like dist3=
//dist1-dist2;. Assume that the operator will never be used to subtract a larger number
//from a smaller one (that is, negative distances are not allowed).
class Distance {
private:
int feet;
float inches;
public:
std::cout << feet << " feet, " << inches << " inches" << std::endl;
};
int main() {
dist3.display();
return 0;
//chap 8.12. Write a program that incorporates both the bMoney class from Exercise 8 and the sterling
//class from Exercise 11. Write conversion operators to convert between bMoney and
//sterling, assuming that one pound (£1.0.0) equals fifty dollars ($50.00). This was the
//approximate exchange rate in the 19th century when the British Empire was at its height
//and the pounds-shillings-pence format was in use. Write a main() program that allows
//the user to enter an amount in either currency and then converts it to the other currency
//and displays the result. Minimize any modifications to the existing bMoney and sterling
//classe
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <cmath>
private:
public:
bMoney() : money(0.0) {}
void getmoney() {
string input;
money = (input);
return money;
money = m;
};
// Forward declaration of class
class sterling;
class sterling {
private:
int pounds;
int shillings;
int pence;
public:
void getSterling() {
cout << "Enter amount in sterling (format: pounds shillings pence): ";
cout << "£" << pounds << "." << shillings << "." << pence << endl;
pounds = static_cast<int>(amount);
double rem = (amount - pounds) * 20;
shillings = static_cast<int>(rem);
return bMoney(dollars);
};
sterling temp;
temp.fromDecimal(pounds_decimal);
return temp;
int main() {
int choice;
bMoney dollars;
dollars.getmoney();
pounds.putSterling();
else if (choice == 2) {
sterling pounds;
pounds.getSterling();
dollars.putmoney();
else {
return 0;
}//8.2 Write a program that substitutes an overloaded += operator for the overloaded + operator
//in the STRPLUS program in this chapter. This operator should allow statements like
//s1 += s2;
//where s2 is added (concatenated) to s1 and the result is left in s1. The operator should
//s3 = s1 += s2;
class String {
private:
char* str;
public:
strcpy(str, s);
strcpy(str, other.str);
~String() {
delete[] str;
strcpy(temp, str);
strcat(temp, other.str);
delete[] str;
str = temp;
return *this;
os << obj.str;
return os;
};
int main() {
String s2("world!");
s1 += s2;
String s3;
s3 = s1 += s2;
return 0;
//8.6 Add to the time class of Exercise 5 the ability to subtract two time values using the
//overloaded (-) operator, and to multiply a time value by a number of type float, using
#include <iostream>
class Time {
private:
int hours;
int minutes;
int seconds;
public:
if (resultSeconds < 0) {
resultSeconds = 0;
}
void display() const {
std::cout << hours << ":" << minutes << ":" << seconds << std::endl;
};
int main() {
Time t3 = t1 - t2;
t3.display();
Time t4 = t1 * 2.5f;
t4.display();//8.4 Create a class Int based on Exercise 1 in Chapter 6. Overload four integer arithmetic
//operators (+, -, *, and /) so that they operate on objects of type Int. If the result of any
//such arithmetic operation exceeds the normal range of ints (in a 32-bit environment)—
//the program. Such a data type might be useful where mistakes caused by arithmetic over?flow are
unacceptable. Hint: To facilitate checking for overflow, perform the calculations
#include <iostream>
#include <climits>
#include<iostream>
class Int {
private:
int value;
public:
Int temp;
temp=value+other.value;
exit(1);
return temp;
exit(1);
return Int(static_cast<int>(result));
};
int i1;
int i2;
i1=10;
i2=5;
int i3;
i3=i1+i2;
return 0;
}//8.5Augment the time class referred to in Exercise 3 to include overloaded increment (++)
//and decrement (--) operators that operate in both prefix and postfix notation and return
#include <iostream>
class Time {
private:
int hours;
int minutes;
int seconds;
public:
void gettime(){
cout<<"enter hours";
cin>>hours;
cout<<"enter minutes";
cin>>minutes;
cout<<"enter seconds";
cin>>seconds;
seconds++;
minutes++;
seconds -= 60;
hours++;
minutes -= 60;
return *this;
++(*this);
return temp;
seconds--;
if (seconds < 0) {
minutes--;
seconds += 60;
if (minutes < 0) {
hours--;
minutes += 60;
return *this;
--(*this);
return temp;
std::cout << hours << ":" << minutes << ":" << seconds << std::endl;
};
int main() {
Time t1;
t1.gettime();
t1.display();
t1.display();
t1.display();
t1.display();
return 0;
//.8.3 Modify the time class from Exercise 3 in Chapter 6 so that instead of a function
//add_time() it uses the overloaded + operator to add two times. Write a program to test
//this class
#include <iostream>
class Time {
private:
int hours;
int minutes;
int seconds;
public:
std::cout << hours << ":" << minutes << ":" << seconds << std::endl;
};
int main() {
t1.display();
t2.display();
Time t3 = t1 + t2;
t3.display();
return 0;
//8.9. Augment the safearay class in the ARROVER3 program in this chapter so that the user
//can specify both the upper and lower bound of the array (indexes running from 100 to
//200, for example). Have the overloaded subscript operator check the index each time the
//array is accessed to ensure that it is not out of bounds. You’ll need to add a two?argument constructor
that specifies the upper and lower bounds. Since we have not yet
//learned how to allocate memory dynamically, the member data will still be an array that
//starts at 0 and runs up to 99, but perhaps you can map the indexes for the safearay into
//different indexes in the real int array. For example, if the client selects a range from 100
//to 175, you could map this into the range from arr[0] to arr[75].
#include <iostream>
class safearray {
protected:
int arr[LIMIT];
public:
int& operator[](int n) {
exit(1);
return arr[n];
};
private:
int lowerBound;
int upperBound;
public:
exit(1);
}
lowerBound = lower;
upperBound = upper;
int& operator[](int n) {
exit(1);
};
int main() {
sa[j] = j * 10;
std::cout << "sa[" << j << "] = " << sa[j] << std::endl;
return 0;
//8.10. For math buffs only: Create a class Polar that represents the points on the plain as polar
//coordinates (radius and angle). Create an overloaded +operator for addition of two
//Polar quantities. “Adding” two points on the plain can be accomplished by adding their
//X coordinates and then adding their Y coordinates. This gives the X and Y coordinates of
//the “answer.” Thus you’ll need to convert two sets of polar coordinates to rectangular
//coordinates, add them, then convert the resulting rectangular representation back to polar
#include <iostream>
#include <cmath>
class Polar {
private:
double radius;
public:
<< " (" << angle * 180 / M_PI << " degrees)" << endl;
// Overloaded + operator
};
int main() {
p1.display();
p2.display();
result.display();
return 0;
}//9.1Imagine a publishing company that markets both book and audiocassette versions of its
//works. Create a class publication that stores the title (a string) and price (type float)
//of a publication. From this class derive two classes: book, which adds a page count (type
//int), and tape, which adds a playing time in minutes (type float). Each of these three
//classes should have a getdata() function to get its data from the user at the keyboard,
//Write a main() program to test the book and tape classes by creating instances of them,
//asking the user to fill in data with getdata(), and then displaying the data with putdata().
#include <iostream>
#include <string>
class publication {
protected:
string title;
float price;
public:
void getdata() {
}
void putdata() const {
};
private:
int pageCount;
public:
void getdata() {
publication::getdata();
publication::putdata();
};
private:
float playingTime;
public:
void getdata() {
publication::getdata();
publication::putdata();
std::cout << "Playing time: " << playingTime << " minutes" << std::endl;
};
int main() {
book b;
tape t;
b.getdata();
t.getdata();
b.putdata();
t.putdata();
return 0;
}//9.2Recall the STRCONV example from Chapter 8. The String class in this example has a
//flaw: It does not protect itself if its objects are initialized to have too many characters.
//(The SZ constant has the value 80.) For example, the definition
//will cause the str array in s to overflow, with unpredictable consequences, such as
//With String as a base class, derive a class Pstring (for “protected string”) that prevents
//buffer overflow when too long a string constant is used in a definition. A new constructor
//in the derived class should copy only SZ–1 characters into str if the string constant is
//longer, but copy the entire constant if it’s shorter. Write a main() program to test different
//lengths of strings.
#include <iostream>
#include <cstring>
class String {
protected:
char str[SZ];
public:
public:
Pstring( char s) {
if (strlen(s) > SZ - 1) {
strncpy(str, s, SZ - 1);
str[SZ - 1] = '\0';
} else {
strcpy(str, s);
};
int main() {
Pstring s2 = "This is a very long string that exceeds the buffer size.";
s1.display();
s2.display();
return 0;
}
/9.3Start with the publication, book, and tape classes of Exercise 1. Add a base class sales
//that holds an array of three floats so that it can record the dollar sales of a particular
//publication for the last three months. Include a getdata() function to get three sales
//amounts from the user, and a putdata() function to display the sales figures. Alter the
//book and tape classes so they are derived from both publication and sales. An object
//of class book or tape should input and output sales data along with its other data. Write
//a main() function to create a book object and a tape object and exercise their input/output
//capabilities.
#include <iostream>
#include <string>
class publication {
protected:
std::string title;
float price;
public:
void getdata() {
}
};
class sales {
protected:
float salesAmount[3];
public:
void getdata() {
std::cout << "Enter sales amount for last three months:" << std::endl;
std::cout << "Sales amount for last three months:" << std::endl;
std::cout << "Month " << i + 1 << ": " << salesAmount[i] << std::endl;
};
private:
int pageCount;
public:
void getdata() {
publication::getdata();
sales::getdata();
publication::putdata();
sales::putdata();
};
private:
float playingTime;
public:
void getdata() {
publication::getdata();
sales::getdata();
publication::putdata();
sales::putdata();
std::cout << "Playing time: " << playingTime << " minutes" << std::endl;
}
};
int main() {
book b;
tape t;
b.getdata();
t.getdata();
b.putdata();
t.putdata();
return 0;
/9.3Start with the publication, book, and tape classes of Exercise 1. Add a base class sales
//that holds an array of three floats so that it can record the dollar sales of a particular
//publication for the last three months. Include a getdata() function to get three sales
//amounts from the user, and a putdata() function to display the sales figures. Alter the
//book and tape classes so they are derived from both publication and sales. An object
//of class book or tape should input and output sales data along with its other data. Write
//a main() function to create a book object and a tape object and exercise their input/output
//capabilities.
#include <iostream>
#include <string>
class publication {
protected:
std::string title;
float price;
public:
void getdata() {
};
class sales {
protected:
float salesAmount[3];
public:
void getdata() {
std::cout << "Enter sales amount for last three months:" << std::endl;
std::cout << "Sales amount for last three months:" << std::endl;
std::cout << "Month " << i + 1 << ": " << salesAmount[i] << std::endl;
};
private:
int pageCount;
public:
void getdata() {
publication::getdata();
sales::getdata();
sales::putdata();
};
private:
float playingTime;
public:
void getdata() {
publication::getdata();
sales::getdata();
publication::putdata();
sales::putdata();
std::cout << "Playing time: " << playingTime << " minutes" << std::endl;
};
int main() {
book b;
tape t;
std::cout << "Enter book details:" << std::endl;
b.getdata();
t.getdata();
b.putdata();
t.putdata();
return 0;
//9.4Assume that the publisher in Exercises 1 and 3 decides to add a third way to distribute
//books: on computer disk, for those who like to do their reading on their laptop. Add a
//disk class that, like book and tape, is derived from publication. The disk class should
//incorporate the same member functions as the other classes. The data item unique to this
//class is the disk type: either CD or DVD. You can use an enum type to store this item.
#include <iostream>
#include <string>
class publication {
protected:
std::string title;
float price;
public:
void getdata() {
};
class sales {
protected:
float salesAmount[3];
public:
void getdata() {
std::cout << "Enter sales amount for last three months:" << std::endl;
std::cout << "Month " << i + 1 << ": " << salesAmount[i] << std::endl;
};
private:
int pageCount;
public:
void getdata() {
publication::getdata();
sales::getdata();
publication::putdata();
sales::putdata();
};
float playingTime;
public:
void getdata() {
publication::getdata();
sales::getdata();
publication::putdata();
sales::putdata();
std::cout << "Playing time: " << playingTime << " minutes" << std::endl;
};
private:
DiskType diskType;
public:
void getdata() {
publication::getdata();
sales::getdata();
char type;
std::cout << "Enter disk type (c for CD, d for DVD): ";
diskType = DiskType::CD;
diskType = DiskType::DVD;
} else {
exit(1);
publication::putdata();
sales::putdata();
if (diskType == DiskType::CD) {
};
int main() {
book b;
tape t;
disk d;
b.getdata();
std::cout << "\nEnter tape details:" << std::endl;
t.getdata();
d.getdata();
b.putdata();
t.putdata();
d.putdata();
return 0;
//9.6 Start with the ARROVER3 program in Chapter 8. Keep the safearay class the same as in//
//that program, and, using inheritance, derive the capability for the user to specify both the
//upper and lower bounds of the array in a constructor. This is similar to Exercise 9 in
//Chapter 8, except that inheritance is used to derive a new class (you can call it safehilo)
#include <iostream>
protected:
int arr[LIMIT];
public:
int& operator[](int n) {
exit(1);
return arr[n];
};
private:
int lowerBound;
int upperBound;
public:
exit(1);
lowerBound = lower;
upperBound = upper;
}
int& operator[](int n) {
exit(1);
};
int main() {
sa[j] = j * 10;
std::cout << "sa[" << j << "] = " << sa[j] << std::endl;
return 0;
//.9.5 Derive a class called employee2 from the employee class in the EMPLOY program in this
//chapter. This new class should add a type double data item called compensation, and
//also an enum type called period to indicate whether the employee is paid hourly, weekly,
//or monthly. For simplicity you can change the manager, scientist, and laborer classes
//so they are derived from employee2 instead of employee. However, note that in many
//circumstances it might be more in the spirit of OOP to create a separate base class called
//compensation and three new classes manager2, scientist2, and laborer2, and use
//multiple inheritance to derive these three classes from the original manager, scientist,
//and laborer classes and from compensation. This way none of the original classes
//needs to be modified.
#include <iostream>
#include <string>
class employee {
protected:
std::string name;
int number;
public:
void getdata() {
};
class employee2 : public employee {
protected:
double compensation;
Period payPeriod;
public:
void getdata() {
employee::getdata();
char period;
std::cout << "Enter pay period (h for hourly, w for weekly, m for monthly): ";
if (period == 'h') {
payPeriod = Period::HOURLY;
payPeriod = Period::WEEKLY;
payPeriod = Period::MONTHLY;
} else {
exit(1);
employee::putdata();
};
private:
std::string title;
public:
void getdata() {
employee2::getdata();
employee2::putdata();
};
private:
int publications;
public:
void getdata() {
employee2::getdata();
employee2::putdata();
};
private:
int yearsOfService;
public:
void getdata() {
employee2::getdata();
employee2::putdata();
};
int main() {
manager2 m;
scientist2 s;
laborer2 l;
m.getdata();
s.getdata();
l.getdata();
m.putdata();
s.putdata();
l.putdata();
return 0;
}
//9.7 Start with the COUNTEN2 program in this chapter. It can increment or decrement a
//counter, but only using prefix notation. Using inheritance, add the ability to use postfix
//notation for both incrementing and decrementing. (See Chapter 8 for a description of
//postfix notation.)
#include <iostream>
class Counter {
protected:
int count;
public:
Counter() : count(0) {}
void increment() {
count++;
void decrement() {
count--;
return count;
};
CounterPP& operator++() {
increment();
return *this;
CounterPP operator++(int) {
increment();
return temp;
CounterPP& operator--() {
decrement();
return *this;
CounterPP operator--(int) {
decrement();
return temp;
};
int main() {
CounterPP c;
std::cout << "Count after prefix increment: " << c.get_count() << std::endl;
c++;
std::cout << "Count after postfix increment: " << c.get_count() << std::endl;
--c;
std::cout << "Count after prefix decrement: " << c.get_count() << std::endl;
c--;
std::cout << "Count after postfix decrement: " << c.get_count() << std::endl;
return 0;
. //There is only one kind of manager in the EMPMULT program in this chapter. Any serious
//company has executives as well as managers. From the manager class derive a class
//called executive. (We’ll assume an executive is a high-end kind of manager.) The addi?tional data in the
executive class will be the size of the employee’s yearly bonus and the
//number of shares of company stock held in his or her stock-option plan. Add the appropriate
//member functions so these data items can be input and displayed along with the other
//manager data.
#include <iostream>
class Manager {
protected:
string name;
int id;
double salary;
public:
void getData() {
void putData() {
};
private:
double bonus;
int shares;
public:
void getData() {
Manager::getData();
void putData() {
Manager::putData();
};
int main() {
Executive exec;
exec.getData();
exec.putData();
return 0;
//9.9 Start with the publication, book, and tape classes of Exercise 1. Suppose you want to
//add the date of publication for both books and tapes. From the publication class, derive
//a new class called publication2 that includes this member data. Then change book and
//tape so they are derived from publication2 instead of publication. Make all the
//necessary changes in member functions so the user can input and output dates along with
//the other data. For the dates, you can use the date class from Exercise 5 in Chapter 6,
//which stores a date as three ints, for month, day, and year
#include <iostream>
class Date {
protected:
int month;
int day;
int year;
public:
void getDate() {
void showDate() {
cout << month << "/" << day << "/" << year;
};
class Publication {
protected:
string title;
double price;
public:
void getData() {
void putData() {
}
};
private:
Date pubDate;
public:
void getData() {
Publication::getData();
pubDate.getDate();
void putData() {
Publication::putData();
pubDate.showDate();
};
private:
int pages;
public:
void getData() {
Publication2::getData();
void putData() {
Publication2::putData();
};
private:
double time;
public:
void getData() {
Publication2::getData();
void putData() {
Publication2::putData();
};
int main() {
Book book;
book.getData();
book.putData();
Tape tape;
tape.getData();
tape.putData();
return 0;
Create a class that imitates part of the functionality of the basic data type int. Call the
class Int (note different capitalization). The only data in this class is an int variable.
play it (it looks just like an int), and to add two Int values.
Write a program that exercises this class by creating one uninitialized and two initialized
Int values, adding the two initialized values and placing the response in the uninitialized
Here's a C++ program that defines a class Int to imitate part of the functionality of the basic data type
int:
Code
#include <iostream>
class Int {
private:
int value;
public:
Int() : value(0) {}
void display() {
};
int main() {
Int uninitialized;
Int initialized1(10);
Int initialized2(20);
// Add the two initialized values and place the response in the uninitialized value
uninitialized = initialized1.add(initialized2);
uninitialized.display();
return 0;
}
Explanation
1. The Int class has a private member variable value of type int.
2. The class includes two constructors: one to initialize Int to 0 and another to initialize it to an int value.
3. The display() member function is used to display the value of an Int object.
4. The add() member function is used to add two Int values and return the result as a new Int object.
5. In the main() function, we create one uninitialized and two initialized Int values, add the two initialized
values, and display the result.
*2. Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent
toll. Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps
track of the number of cars that have gone by, and of the total amount of money collected.Model this
tollbooth with a class called tollBooth. The two data items are a type
unsigned int to hold the total number of cars, and a type double to hold the total amount
payingCar() increments the car total and adds 0.50 to the cash total. Another function,
called nopayCar(), increments the car total but adds nothing to the cash total. Finally, a
member function called display() displays the two totals. Make appropriate member
functions const.
Include a program to test this class. This program should allow the user to push one key
to count a paying car, and another to count a nonpaying car. Pushing the Esc key should
cause the program to print out the total cars and total cash and then exit.
Here's a C++ program that models a tollbooth with a class called tollBooth:
Code
#include <iostream>
class tollBooth {
private:
double totalCash;
public:
void payingCar() {
totalCars++;
totalCash += 0.50;
void nopayCar() {
totalCars++;
};
int main() {
tollBooth booth;
char input;
while (true) {
cout << "Press 'p' for paying car, 'n' for nonpaying car, or 'Esc' to exit." << endl;
if (input == 'p') {
booth.payingCar();
booth.nopayCar();
booth.display();
break;
} else {
return 0;
Explanation
1. The tollBooth class has two private member variables: totalCars of type unsigned int and totalCash of
type double.
3. The payingCar() member function increments totalCars and adds 0.50 to totalCash.
4. The nopayCar() member function increments totalCars but does not add anything to totalCash.
6. In the main() function, the user is prompted to press a key to count a paying car, a nonpaying car, or to
exit.
7. Based on the user's input, the corresponding member function is called.
Create a class called time that has separate int member data for hours, minutes, and
seconds. One constructor should initialize this data to 0, and another should initialize it
to fixed values. Another member function should display it, in 11:59:59 format. The final
member function should add two objects of type time passed as arguments.
A main() program should create two initialized time objects (should they be const?) and
one that isn’t initialized. Then it should add the two initialized values together, leaving the
result in the third time variable. Finally it should display the value of this third variable.
Make appropriate member functions cons8. When the user presses the Esc key, the program displays the
totals and exits.
Here's a C++ program that defines a time class with the specified functionality:
Code
#include <iostream>
#include <iomanip>
class time {
private:
int hours;
int minutes;
int seconds;
public:
};
int main() {
time t3;
t3 = t1.add(t2);
// Display the result
t3.display();
return 0;
Explanation
1. The time class has three private member variables: hours, minutes, and seconds.
2. The class includes two constructors: one to initialize time to 0 and another to initialize it to fixed
values.
3. The display() member function displays the time in the format 11:59:59.
4. The add() member function adds two time objects and returns the result as a new time object.
5. In the main() function, we create two initialized time objects (t1 and t2) and one uninitialized time
object (t3).
6. We add t1 and t2 together using the add() member function and store the result in t3.
Create an employee class, basing it on Exercise 4 of Chapter 4. The member data should
comprise an int for storing the employee number and a float for storing the employee’s
compensation. Member functions should allow the user to enter this data and display it.
Here's a C++ program that defines an employee class with the specified functionality:
Code
#include <iostream>
private:
int employeeNumber;
float compensation;
public:
void enterData() {
};
int main() {
employee employees[numEmployees];
cout << "Enter data for Employee " << (i + 1) << ":" << endl;
employees[i].enterData();
}
// Display data for each employee
employees[i].displayData();
return 0;
Explanation
1. The employee class has two private member variables: employeeNumber of type int and
compensation of type float.
2. The class includes two member functions: enterData() to enter employee data and displayData() to
display employee data.
3. In the main() function, we create an array of employee objects to store data for three employees.
4. We use a loop to enter data for each employee using the enterData() member function.
5. We use another loop to display data for each employee using the displayData() member function.
Write a main() that allows the user to enter data for three employees and display it.
Start with the date structure in Exercise 5 in Chapter 4 and transform it into a date
class. Its member data should consist of three ints: month, day, and year. It should also
have two member functions: getdate(), which allows the user to enter a date in
Here's a C++ program that defines a date class with the specified functionality:
Code
#include <iostream>
class date {
private:
int month;
int day;
int year;
public:
void getdate() {
char slash;
cin >> month >> slash >> day >> slash >> year;
cout << month << "/" << day << "/" << year << endl;
};
int main() {
date d;
d.getdate();
d.showdate();
return 0;
Explanation
1. The date class has three private member variables: month, day, and year, all of type int.
2. The class includes two member functions: getdate() to enter a date and showdate() to display a date.
3. In the getdate() function, we use a char variable slash to ignore the slash characters in the input date.
4. In the main() function, we create a date object d, call getdate() to enter a date, and then call
showdate() to display the entered date.
Extend the employee class of Exercise 4 to include a date class (see Exercise 5) and an
etype enum (see Exercise 6 in Chapter 4). An object of the date class should be used to
hold the date of first employment; that is, the date when the employee was hired. The
etype variable should hold the employee’s type: laborer, secretary, manager, and so on.
These two items will be private member data in the employee definition, just like the
employee number and salary. You’ll need to extend the getemploy() and putemploy()
functions to obtain this new information from the user and display it. These functions will
probably need switch statements to handle the etype variable. Write a main() program that
allows the user to enter data for three employee variables and then displays this data.
Here's a C++ program that extends the employee class to include a date class and an etype enum:
Code
#include <iostream>
class date {
private:
int month;
int day;
int year;
public:
void getdate() {
char slash;
cin >> month >> slash >> day >> slash >> year;
cout << month << "/" << day << "/" << year;
};
// Employee class
class employee {
private:
int employeeNumber;
float compensation;
date hireDate;
etype employeeType;
public:
hireDate.getdate();
char type;
switch (type) {
case 'l':
employeeType = laborer;
break;
case 's':
employeeType = secretary;
break;
case 'm':
employeeType = manager;
break;
default:
employeeType = laborer;
hireDate.showdate();
switch (employeeType) {
case laborer:
break;
case secretary:
break;
case manager:
break;
};
int main() {
employee employees[numEmployees];
cout << "Enter data for Employee " << (i + 1) << ":" << endl;
employees[i].getemploy();
}
// Display data for each employee
employees[i].putemploy();
return 0;
Explanation
1. We define an etype enum with values for laborer, secretary, and manager.
2. We define a date class with member functions to enter and display a date.
3. We extend the employee class to include a date object for the hire date and an etype variable for the
employee type.
4. We modify the getemploy() function to enter the hire date and employee type, and the putemploy()
function to display this information.
5. In the main() function, we create an array of employee objects and enter and display data for each
employee.
In ocean navigation, locations are measured in degrees and minutes of latitude and longi-
tude. Thus if you’re lying off the mouth of Papeete Harbor in Tahiti, your location is 149
degrees 34.8 minutes west longitude, and 17 degrees 31.5 minutes south latitude. This iswritten as
149°34.8’ W, 17°31.5’ S. There are 60 minutes in a degree. (An older system
also divided a minute into 60 seconds, but the modern approach is to use decimal minutes
instead.) Longitude is measured from 0 to 180 degrees, east or west from Greenwich,
for minutes, and a char for the direction letter (N, S, E, or W). This class can hold either
a latitude variable or a longitude variable. Write one member function to obtain an angle
value (in degrees and minutes) and a direction from the user, and a second to display the
main() program that displays an angle initialized with the constructor, and then, within a
loop, allows the user to input any angle value, and then displays the value. You can use
the hex character constant ‘\xF8’, which usually prints a degree (°) symbol.
Here's a C++ program that defines an angle class with the specified functionality:
Code
#include <iostream>
#include <iomanip>
class angle {
private:
int degrees;
float minutes;
char direction;
public:
void getangle() {
cout << degrees << "\xF8" << setprecision(1) << fixed << minutes << "\' " << direction;
};
int main() {
a.displayangle();
while (true) {
userAngle.getangle();
userAngle.displayangle();
if (cont != 'y') {
break;
return 0;
Explanation
1. The angle class has three private member variables: degrees of type int, minutes of type float, and
direction of type char.
2. The class includes a constructor to initialize an angle object, a getangle() member function to enter an
angle value, and a displayangle() member function to display an angle value.
3. In the main() function, we create an angle object a and initialize it with the constructor.
4. We display the initialized angle and then enter a loop where the user can input angle values and
display them.
Create a class that includes a data member that holds a “serial number” for each object
created from the class. That is, the first object created will be numbered 1, the second 2,
and so on.
To do this, you’ll need another data member that records a count of how many objects
have been created so far. (This member should apply to the class as a whole; not to
individual objects. What keyword specifies this?) Then, as each object is created, its
constructor can examine this count member variable to determine the appropriate serial
write a main() program that creates three objects and queries each one about its serial
Here's a C++ program that defines a class with a serial number for each object:
Code
#include <iostream>
class MyClass {
private:
int serialNumber;
public:
MyClass() {
cout << "I am object number " << serialNumber << endl;
};
int MyClass::objectCount = 0;
int main() {
MyClass obj1;
MyClass obj2;
MyClass obj3;
obj1.reportSerialNumber();
obj2.reportSerialNumber();
obj3.reportSerialNumber();
return 0;
Explanation
1. We define a class MyClass with a private member variable serialNumber to store the serial number of
each object.
2. We use a static member variable objectCount to count the number of objects created. The static
keyword specifies that this member variable applies to the class as a whole, not to individual objects.
3. In the constructor, we increment the objectCount and assign it to the serialNumber of the new object.
5. In the main() function, we create three objects and query each one about its serial number using the
reportSerialNumber() function.
Output
I am object number 1
I am object number 2
I am object number 3
Transform the fraction structure from Exercise 8 in Chapter 4 into a fraction class.
Member data is the fraction’s numerator and denominator. Member functions should
accept input from the user in the form 3/5, and output the fraction’s value in the same
format. Another member function should add two fraction values. Write a main() program
that allows the user to repeatedly input two fractions and then displays their sum. After
Here's a C++ program that defines a fraction class with the specified functionality:
Code
#include <iostream>
class fraction {
private:
int numerator;
int denominator;
public:
void getfraction() {
char slash;
fraction result;
result.numerator = newNumerator;
result.denominator = newDenominator;
return result;
};
int main() {
char cont;
do {
f1.getfraction();
f2.getfraction();
sum = f1.add(f2);
f2.displayfraction();
sum.displayfraction();
return 0;
Explanation
1. The fraction class has two private member variables: numerator and denominator.
2. The class includes member functions to enter a fraction value (getfraction()), display a fraction value
(displayfraction()), and add two fraction values (add()).
3. In the main() function, we create two fraction objects f1 and f2, and a third object sum to store their
sum.
4. We use a loop to repeatedly input two fractions, add them, and display their sum.
5. After each operation, we ask the user if they want to continue. If they choose not to, the loop exits.