0% found this document useful (0 votes)
0 views

Programming

The document contains several C++ class implementations demonstrating operator overloading for various data types, including Distance, bMoney, sterling, String, Time, and Int. Key functionalities include arithmetic operations, conversions between currencies, and array bounds checking. Each class is accompanied by a main function to test its features.

Uploaded by

Areesha Tahir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Programming

The document contains several C++ class implementations demonstrating operator overloading for various data types, including Distance, bMoney, sterling, String, Time, and Int. Key functionalities include arithmetic operations, conversions between currencies, and array bounds checking. Each class is accompanied by a main function to test its features.

Uploaded by

Areesha Tahir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

//8.1.

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:

Distance(int ft = 0, float in = 0.0f) : feet(ft), inches(in) {}

Distance operator-(const Distance& other) const {

int totalInches1 = feet * 12 + inches;

int totalInches2 = other.feet * 12 + other.inches;

int resultInches = totalInches1 - totalInches2;

int resultFeet = resultInches / 12;

float resultInchesFinal = resultInches % 12;

return Distance(resultFeet, resultInchesFinal);

void display() const {

std::cout << feet << " feet, " << inches << " inches" << std::endl;

};
int main() {

Distance dist1(10, 5.5f);

Distance dist2(3, 7.2f);

Distance dist3 = dist1 - dist2;

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>

using namespace std;

// -------------------- bMoney class --------------------


class bMoney {

private:

long double money;

public:

bMoney() : money(0.0) {}

bMoney(long double m) : money(m) {}

void getmoney() {

string input;

cout << "Enter amount in dollars (e.g. $1,234.56): ";

cin >> input;

input.erase(remove(input.begin(), input.end(), '$'), input.end());

input.erase(remove(input.begin(), input.end(), ','), input.end());

money = (input);

void putmoney() const {

cout << fixed << setprecision(2);

cout << "$" << money << endl;

long double getAmount() const {

return money;

void setAmount(long double m) {

money = m;

};
// Forward declaration of class

class sterling;

// bMoney to sterling conversion

class sterling {

private:

int pounds;

int shillings;

int pence;

public:

sterling() : pounds(0), shillings(0), pence(0) {}

sterling(int p, int s, int d) : pounds(p), shillings(s), pence(d) {}

void getSterling() {

cout << "Enter amount in sterling (format: pounds shillings pence): ";

cin >> pounds >> shillings >> pence;

void putSterling() const {

cout << "£" << pounds << "." << shillings << "." << pence << endl;

double toDecimal() const {

return pounds + shillings / 20.0 + pence / 240.0;

void fromDecimal(double amount) {

pounds = static_cast<int>(amount);
double rem = (amount - pounds) * 20;

shillings = static_cast<int>(rem);

pence = static_cast<int>((rem - shillings) * 12);

// Conversion from sterling to bMoney

operator bMoney() const {

double dollars = toDecimal() * 50.0; // 1 pound = 50 dollars

return bMoney(dollars);

};

// Conversion from bMoney to sterling

bMoney::operator sterling() const {

double pounds_decimal = money / 50.0;

sterling temp;

temp.fromDecimal(pounds_decimal);

return temp;

// -------------------- main program --------------------

int main() {

int choice;

cout << "Currency Converter\n";

cout << "------------------\n";

cout << "1. Convert Dollars to Sterling\n";

cout << "2. Convert Sterling to Dollars\n";

cout << "Enter choice (1 or 2): ";

cin >> choice;


if (choice == 1) {

bMoney dollars;

dollars.getmoney();

sterling pounds = dollars; // implicit conversion

cout << "Equivalent in Sterling: ";

pounds.putSterling();

else if (choice == 2) {

sterling pounds;

pounds.getSterling();

bMoney dollars = pounds; // implicit conversion

cout << "Equivalent in Dollars: ";

dollars.putmoney();

else {

cout << "Invalid choice.\n";

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

//also permit the results of the operation to be used in other calculations, as in

//s3 = s1 += s2;

class String {
private:

char* str;

public:

String(const char* s = "") {

str = new char[strlen(s) + 1];

strcpy(str, s);

String(const String& other) {

str = new char[strlen(other.str) + 1];

strcpy(str, other.str);

~String() {

delete[] str;

String& operator+=(const String& other) {

char* temp = new char[strlen(str) + strlen(other.str) + 1];

strcpy(temp, str);

strcat(temp, other.str);

delete[] str;

str = temp;

return *this;

friend std::ostream& operator<<(std::ostream& os, const String& obj) {

os << obj.str;
return os;

};

int main() {

String s1("Hello, ");

String s2("world!");

s1 += s2;

std::cout << s1 << std::endl;

String s3;

s3 = s1 += s2;

std::cout << s3 << std::endl;

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

//the overloaded (*) operator

#include <iostream>

class Time {

private:

int hours;

int minutes;
int seconds;

public:

Time(int h = 0, int m = 0, int s = 0) : hours(h), minutes(m), seconds(s) {}

Time operator-(const Time& other) const {

int totalSeconds1 = hours * 3600 + minutes * 60 + seconds;

int totalSeconds2 = other.hours * 3600 + other.minutes * 60 + other.seconds;

int resultSeconds = totalSeconds1 - totalSeconds2;

if (resultSeconds < 0) {

resultSeconds = 0;

int resultHours = resultSeconds / 3600;

int resultMinutes = (resultSeconds % 3600) / 60;

int resultSecondsFinal = resultSeconds % 60;

return Time(resultHours, resultMinutes, resultSecondsFinal);

Time operator*(float multiplier) const {

float totalSeconds = (hours * 3600 + minutes * 60 + seconds) * multiplier;

int resultHours = static_cast<int>(totalSeconds / 3600);

int resultMinutes = static_cast<int>((totalSeconds - resultHours * 3600) / 60);

int resultSeconds = static_cast<int>(totalSeconds - resultHours * 3600 - resultMinutes * 60);

return Time(resultHours, resultMinutes, resultSeconds);

}
void display() const {

std::cout << hours << ":" << minutes << ":" << seconds << std::endl;

};

int main() {

Time t1(10, 30, 0);

Time t2(2, 45, 0);

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)—

//from 2,147,483,648 to –2,147,483,647—have the operator print a warning and terminate

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

//using type long double. Write a program to test this class.

#include <iostream>

#include <climits>

#include<iostream>

using namespace std;

class Int {
private:

int value;

public:

Int(int val = 0) : value(val) {}

Int operator+( Int other) {

Int temp;

temp=value+other.value;

if (temp > INT_MAX ||temp < INT_MIN) {

cout << "Warning: Arithmetic overflow!" << std::endl;

exit(1);

return temp;

Int operator-(const Int& other) const {

long double result = static_cast<long double>(value) - other.value;

if (result > INT_MAX || result < INT_MIN) {

std::cerr << "Warning: Arithmetic overflow!" << std::endl;

exit(1);

return Int(static_cast<int>(result));

};

int main (){

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

//values. Add statements to main() to test these operators.

#include <iostream>

using namespace std;

class Time {

private:

int hours;

int minutes;

int seconds;

public:

Time(int h = 0, int m = 0, int s = 0) : hours(h), minutes(m), seconds(s) {}

void gettime(){

cout<<"enter hours";

cin>>hours;

cout<<"enter minutes";

cin>>minutes;

cout<<"enter seconds";
cin>>seconds;

Time operator++() { // Prefix increment

seconds++;

if (seconds >= 60) {

minutes++;

seconds -= 60;

if (minutes >= 60) {

hours++;

minutes -= 60;

return *this;

Time operator++(int) { // Postfix increment

Time temp = *this;

++(*this);

return temp;

Time& operator--() { // Prefix decrement

seconds--;

if (seconds < 0) {

minutes--;

seconds += 60;

if (minutes < 0) {

hours--;
minutes += 60;

return *this;

Time operator--(int) { // Postfix decrement

Time temp = *this;

--(*this);

return temp;

void display() const {

std::cout << hours << ":" << minutes << ":" << seconds << std::endl;

};

int main() {

Time t1;

cout<<"enter the value of t1"<<endl;

t1.gettime();

t1.display();

++t1; // Prefix increment

t1.display();

t1++; // Postfix increment

t1.display();

--t1; // Prefix decrement


t1.display();

t1--; // Postfix decrement

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>

using namespace std;

class Time {

private:

int hours;

int minutes;

int seconds;

public:

Time(int h = 0, int m = 0, int s = 0) : hours(h), minutes(m), seconds(s) {}

Time operator+( Time t2) {

int totalSeconds = (hours * 3600 + minutes * 60 + seconds) + (t2.hours * 3600 + t2.minutes * 60 +


t2.seconds);

int newHours = totalSeconds / 3600;

int newMinutes = (totalSeconds % 3600) / 60;

int newSeconds = totalSeconds % 60;

return Time(newHours, newMinutes, newSeconds);


}

void display() const {

std::cout << hours << ":" << minutes << ":" << seconds << std::endl;

};

int main() {

Time t1(10, 30, 0);

t1.display();

Time t2(2, 45, 0);

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>

const int LIMIT = 100;

class safearray {

protected:

int arr[LIMIT];

public:

int& operator[](int n) {

if (n < 0 || n >= LIMIT) {

std::cout << "\nIndex out of bounds";

exit(1);

return arr[n];

};

class safearrayhilo : public safearray {

private:

int lowerBound;

int upperBound;

public:

safearrayhilo(int lower, int upper) {

if (upper - lower + 1 > LIMIT) {

std::cout << "\nArray size exceeds limit";

exit(1);

}
lowerBound = lower;

upperBound = upper;

int& operator[](int n) {

if (n < lowerBound || n > upperBound) {

std::cout << "\nIndex out of bounds";

exit(1);

return arr[n - lowerBound];

};

int main() {

safearrayhilo sa(100, 200);

for (int j = 100; j <= 200; j++) {

sa[j] = j * 10;

for (int j = 100; j <= 200; j++) {

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>

using namespace std;

class Polar {

private:

double radius;

double angle; // in radians

public:

Polar(double r = 0.0, double a = 0.0) : radius(r), angle(a) {}

void display() const {

cout << "Radius: " << radius

<< ", Angle (radians): " << angle

<< " (" << angle * 180 / M_PI << " degrees)" << endl;

// Overloaded + operator

Polar operator+( Polar p) {

// Convert both to Cartesian

double x1 = radius * cos(angle);

double y1 = radius * sin(angle);


double x2 = p.radius * cos(p.angle);

double y2 = p.radius * sin(p.angle);

// Add Cartesian coordinates

double x_sum = x1 + x2;

double y_sum = y1 + y2;

// Convert back to Polar

double r_result = sqrt(x_sum * x_sum + y_sum * y_sum);

double a_result = atan2(y_sum, x_sum);

return Polar(r_result, a_result);

};

int main() {

// Create two polar points

Polar p1(5, M_PI / 4); // 5 units at 45 degrees

Polar p2(3, M_PI / 6); // 3 units at 30 degrees

cout << "P1: ";

p1.display();

cout << "P2: ";

p2.display();

Polar result = p1 + p2;


cout << "\nP1 + P2 (resultant vector): ";

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,

//and a putdata() function to display its data.

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

using namespace std;

class publication {

protected:

string title;

float price;

public:

void getdata() {

cout << "Enter title: ";

cin >> title;

cout << "Enter price: ";

cin >> price;

}
void putdata() const {

cout << "Title: " << title << std::endl;

cout << "Price: " << price << std::endl;

};

class book : public publication {

private:

int pageCount;

public:

void getdata() {

publication::getdata();

cout << "Enter page count: ";

cin >> pageCount;

void putdata() const {

publication::putdata();

std::cout << "Page count: " << pageCount << std::endl;

};

class tape : public publication {

private:

float playingTime;

public:
void getdata() {

publication::getdata();

cout << "Enter playing time (minutes): ";

cin >> playingTime;

void putdata() const {

publication::putdata();

std::cout << "Playing time: " << playingTime << " minutes" << std::endl;

};

int main() {

book b;

tape t;

cout << "Enter book details:" << std::endl;

b.getdata();

cout << "\nEnter tape details:" << std::endl;

t.getdata();

cout << "\nBook details:" << std::endl;

b.putdata();

std::cout << "\nTape details:" << std::endl;

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

//String s = “This string will surely exceed the width of the “

//“screen, which is what the SZ constant represents.”;

//will cause the str array in s to overflow, with unpredictable consequences, such as

//crashing the system.

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

const int SZ = 80;

class String {

protected:

char str[SZ];

public:

String() { str[0] = '\0'; }

String(const char* s) { strcpy(str, s); }

void display() const { std::cout << str; }


};

class Pstring : public String {

public:

Pstring( char s) {

if (strlen(s) > SZ - 1) {

strncpy(str, s, SZ - 1);

str[SZ - 1] = '\0';

} else {

strcpy(str, s);

};

int main() {

String s1 = "This is a short string.";

Pstring s2 = "This is a very long string that exceeds the buffer size.";

std::cout << "s1: ";

s1.display();

std::cout << std::endl;

std::cout << "s2: ";

s2.display();

std::cout << std::endl;

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() {

std::cout << "Enter title: ";

std::cin >> title;

std::cout << "Enter price: ";

std::cin >> price;

void putdata() const {

std::cout << "Title: " << title << std::endl;

std::cout << "Price: " << price << std::endl;

}
};

class sales {

protected:

float salesAmount[3];

public:

void getdata() {

std::cout << "Enter sales amount for last three months:" << std::endl;

for (int i = 0; i < 3; i++) {

std::cout << "Month " << i + 1 << ": ";

std::cin >> salesAmount[i];

void putdata() const {

std::cout << "Sales amount for last three months:" << std::endl;

for (int i = 0; i < 3; i++) {

std::cout << "Month " << i + 1 << ": " << salesAmount[i] << std::endl;

};

class book : public publication, public sales {

private:

int pageCount;

public:

void getdata() {
publication::getdata();

sales::getdata();

std::cout << "Enter page count: ";

std::cin >> pageCount;

void putdata() const {

publication::putdata();

sales::putdata();

std::cout << "Page count: " << pageCount << std::endl;

};

class tape : public publication, public sales {

private:

float playingTime;

public:

void getdata() {

publication::getdata();

sales::getdata();

std::cout << "Enter playing time (minutes): ";

std::cin >> playingTime;

void putdata() const {

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();

std::cout << "\nEnter tape details:" << std::endl;

t.getdata();

std::cout << "\nBook details:" << std::endl;

b.putdata();

std::cout << "\nTape details:" << std::endl;

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() {

std::cout << "Enter title: ";

std::cin >> title;

std::cout << "Enter price: ";

std::cin >> price;

void putdata() const {

std::cout << "Title: " << title << std::endl;

std::cout << "Price: " << price << std::endl;

};

class sales {

protected:

float salesAmount[3];

public:
void getdata() {

std::cout << "Enter sales amount for last three months:" << std::endl;

for (int i = 0; i < 3; i++) {

std::cout << "Month " << i + 1 << ": ";

std::cin >> salesAmount[i];

void putdata() const {

std::cout << "Sales amount for last three months:" << std::endl;

for (int i = 0; i < 3; i++) {

std::cout << "Month " << i + 1 << ": " << salesAmount[i] << std::endl;

};

class book : public publication, public sales {

private:

int pageCount;

public:

void getdata() {

publication::getdata();

sales::getdata();

std::cout << "Enter page count: ";

std::cin >> pageCount;

void putdata() const {


publication::putdata();

sales::putdata();

std::cout << "Page count: " << pageCount << std::endl;

};

class tape : public publication, public sales {

private:

float playingTime;

public:

void getdata() {

publication::getdata();

sales::getdata();

std::cout << "Enter playing time (minutes): ";

std::cin >> playingTime;

void putdata() const {

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();

std::cout << "\nEnter tape details:" << std::endl;

t.getdata();

std::cout << "\nBook details:" << std::endl;

b.putdata();

std::cout << "\nTape details:" << std::endl;

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.

//The user could select the appropriate type by typing c or d.

#include <iostream>

#include <string>

class publication {

protected:

std::string title;

float price;
public:

void getdata() {

std::cout << "Enter title: ";

std::cin >> title;

std::cout << "Enter price: ";

std::cin >> price;

void putdata() const {

std::cout << "Title: " << title << std::endl;

std::cout << "Price: " << price << std::endl;

};

class sales {

protected:

float salesAmount[3];

public:

void getdata() {

std::cout << "Enter sales amount for last three months:" << std::endl;

for (int i = 0; i < 3; i++) {

std::cout << "Month " << i + 1 << ": ";

std::cin >> salesAmount[i];

void putdata() const {


std::cout << "Sales amount for last three months:" << std::endl;

for (int i = 0; i < 3; i++) {

std::cout << "Month " << i + 1 << ": " << salesAmount[i] << std::endl;

};

enum class DiskType { CD, DVD };

class book : public publication, public sales {

private:

int pageCount;

public:

void getdata() {

publication::getdata();

sales::getdata();

std::cout << "Enter page count: ";

std::cin >> pageCount;

void putdata() const {

publication::putdata();

sales::putdata();

std::cout << "Page count: " << pageCount << std::endl;

};

class tape : public publication, public sales {


private:

float playingTime;

public:

void getdata() {

publication::getdata();

sales::getdata();

std::cout << "Enter playing time (minutes): ";

std::cin >> playingTime;

void putdata() const {

publication::putdata();

sales::putdata();

std::cout << "Playing time: " << playingTime << " minutes" << std::endl;

};

class disk : public publication, public sales {

private:

DiskType diskType;

public:

void getdata() {

publication::getdata();

sales::getdata();

char type;

std::cout << "Enter disk type (c for CD, d for DVD): ";

std::cin >> type;


if (type == 'c') {

diskType = DiskType::CD;

} else if (type == 'd') {

diskType = DiskType::DVD;

} else {

std::cerr << "Invalid disk type." << std::endl;

exit(1);

void putdata() const {

publication::putdata();

sales::putdata();

if (diskType == DiskType::CD) {

std::cout << "Disk type: CD" << std::endl;

} else if (diskType == DiskType::DVD) {

std::cout << "Disk type: DVD" << std::endl;

};

int main() {

book b;

tape t;

disk d;

std::cout << "Enter book details:" << std::endl;

b.getdata();
std::cout << "\nEnter tape details:" << std::endl;

t.getdata();

std::cout << "\nEnter disk details:" << std::endl;

d.getdata();

std::cout << "\nBook details:" << std::endl;

b.putdata();

std::cout << "\nTape details:" << std::endl;

t.putdata();

std::cout << "\nDisk details:" << std::endl;

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)

//instead of modifying the original class

#include <iostream>

const int LIMIT = 100;


class safearray {

protected:

int arr[LIMIT];

public:

int& operator[](int n) {

if (n < 0 || n >= LIMIT) {

std::cout << "\nIndex out of bounds";

exit(1);

return arr[n];

};

class safearrayhilo : public safearray {

private:

int lowerBound;

int upperBound;

public:

safearrayhilo(int lower, int upper) {

if (upper - lower + 1 > LIMIT) {

std::cout << "\nArray size exceeds limit";

exit(1);

lowerBound = lower;

upperBound = upper;

}
int& operator[](int n) {

if (n < lowerBound || n > upperBound) {

std::cout << "\nIndex out of bounds";

exit(1);

return arr[n - lowerBound];

};

int main() {

safearrayhilo sa(100, 200);

for (int j = 100; j <= 200; j++) {

sa[j] = j * 10;

for (int j = 100; j <= 200; j++) {

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>

enum class Period { HOURLY, WEEKLY, MONTHLY };

class employee {

protected:

std::string name;

int number;

public:

void getdata() {

std::cout << "Enter name: ";

std::cin >> name;

std::cout << "Enter number: ";

std::cin >> number;

void putdata() const {

std::cout << "Name: " << name << std::endl;

std::cout << "Number: " << number << std::endl;

};
class employee2 : public employee {

protected:

double compensation;

Period payPeriod;

public:

void getdata() {

employee::getdata();

std::cout << "Enter compensation: ";

std::cin >> compensation;

char period;

std::cout << "Enter pay period (h for hourly, w for weekly, m for monthly): ";

std::cin >> period;

if (period == 'h') {

payPeriod = Period::HOURLY;

} else if (period == 'w') {

payPeriod = Period::WEEKLY;

} else if (period == 'm') {

payPeriod = Period::MONTHLY;

} else {

std::cerr << "Invalid pay period." << std::endl;

exit(1);

void putdata() const {

employee::putdata();

std::cout << "Compensation: " << compensation << std::endl;


if (payPeriod == Period::HOURLY) {

std::cout << "Pay period: Hourly" << std::endl;

} else if (payPeriod == Period::WEEKLY) {

std::cout << "Pay period: Weekly" << std::endl;

} else if (payPeriod == Period::MONTHLY) {

std::cout << "Pay period: Monthly" << std::endl;

};

class manager2 : public employee2 {

private:

std::string title;

public:

void getdata() {

employee2::getdata();

std::cout << "Enter title: ";

std::cin >> title;

void putdata() const {

employee2::putdata();

std::cout << "Title: " << title << std::endl;

};

class scientist2 : public employee2 {

private:
int publications;

public:

void getdata() {

employee2::getdata();

std::cout << "Enter number of publications: ";

std::cin >> publications;

void putdata() const {

employee2::putdata();

std::cout << "Number of publications: " << publications << std::endl;

};

class laborer2 : public employee2 {

private:

int yearsOfService;

public:

void getdata() {

employee2::getdata();

std::cout << "Enter years of service: ";

std::cin >> yearsOfService;

void putdata() const {

employee2::putdata();

std::cout << "Years of service: " << yearsOfService << std::endl;


}

};

int main() {

manager2 m;

scientist2 s;

laborer2 l;

std::cout << "Enter manager details:" << std::endl;

m.getdata();

std::cout << "\nEnter scientist details:" << std::endl;

s.getdata();

std::cout << "\nEnter laborer details:" << std::endl;

l.getdata();

std::cout << "\nManager details:" << std::endl;

m.putdata();

std::cout << "\nScientist details:" << std::endl;

s.putdata();

std::cout << "\nLaborer details:" << std::endl;

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

int get_count() const {

return count;

};

class CounterPP : public Counter {


public:

CounterPP& operator++() {

increment();

return *this;

CounterPP operator++(int) {

CounterPP temp = *this;

increment();

return temp;

CounterPP& operator--() {

decrement();

return *this;

CounterPP operator--(int) {

CounterPP temp = *this;

decrement();

return temp;

};

int main() {

CounterPP c;

std::cout << "Initial count: " << c.get_count() << std::endl;


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

using namespace std;

// Assuming the Manager class is defined as follows

class Manager {

protected:

string name;
int id;

double salary;

public:

void getData() {

cout << "Enter name: "; cin >> name;

cout << "Enter ID: "; cin >> id;

cout << "Enter salary: "; cin >> salary;

void putData() {

cout << "Name: " << name << endl;

cout << "ID: " << id << endl;

cout << "Salary: " << salary << endl;

};

// Deriving the Executive class from the Manager class

class Executive : public Manager {

private:

double bonus;

int shares;

public:

void getData() {

Manager::getData();

cout << "Enter bonus: "; cin >> bonus;

cout << "Enter shares: "; cin >> shares;

void putData() {
Manager::putData();

cout << "Bonus: " << bonus << endl;

cout << "Shares: " << shares << endl;

};

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>

using namespace std;

// Date class definition

class Date {

protected:

int month;
int day;

int year;

public:

void getDate() {

cout << "Enter month: "; cin >> month;

cout << "Enter day: "; cin >> day;

cout << "Enter year: "; cin >> year;

void showDate() {

cout << month << "/" << day << "/" << year;

};

// Publication class definition

class Publication {

protected:

string title;

double price;

public:

void getData() {

cout << "Enter title: "; cin >> title;

cout << "Enter price: "; cin >> price;

void putData() {

cout << "Title: " << title << endl;

cout << "Price: " << price << endl;

}
};

// Publication2 class definition

class Publication2 : public Publication {

private:

Date pubDate;

public:

void getData() {

Publication::getData();

pubDate.getDate();

void putData() {

Publication::putData();

cout << "Publication Date: ";

pubDate.showDate();

cout << endl;

};

// Book class definition

class Book : public Publication2 {

private:

int pages;

public:

void getData() {

Publication2::getData();

cout << "Enter pages: "; cin >> pages;


}

void putData() {

Publication2::putData();

cout << "Pages: " << pages << endl;

};

// Tape class definition

class Tape : public Publication2 {

private:

double time;

public:

void getData() {

Publication2::getData();

cout << "Enter time: "; cin >> time;

void putData() {

Publication2::putData();

cout << "Time: " << time << endl;

};

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.

Include member functions to initialize an Int to 0, to initialize it to an int value, to dis-

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

value, and then displaying this result.

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>

using namespace std;

class Int {

private:

int value;

public:

// Constructor to initialize Int to 0

Int() : value(0) {}

// Constructor to initialize Int to an int value

Int(int val) : value(val) {}


// Member function to display Int

void display() {

cout << value;

// Member function to add two Int values

Int add(Int other) {

return Int(value + other.value);

};

int main() {

// Create one uninitialized and two initialized Int values

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);

// Display the result

cout << "Result: ";

uninitialized.display();

cout << endl;

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

of money collected. A constructor initializes both of these to 0. A member function called

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>

using namespace std;

class tollBooth {
private:

unsigned int totalCars;

double totalCash;

public:

// Constructor to initialize totalCars and totalCash to 0

tollBooth() : totalCars(0), totalCash(0.0) {}

// Member function to count a paying car

void payingCar() {

totalCars++;

totalCash += 0.50;

// Member function to count a nonpaying car

void nopayCar() {

totalCars++;

// Member function to display the totals

void display() const {

cout << "Total Cars: " << totalCars << endl;

cout << "Total Cash: $" << totalCash << endl;

};

int main() {

tollBooth booth;

char input;
while (true) {

cout << "Press 'p' for paying car, 'n' for nonpaying car, or 'Esc' to exit." << endl;

cin >> input;

if (input == 'p') {

booth.payingCar();

} else if (input == 'n') {

booth.nopayCar();

} else if (input == 27) { // ASCII value for Esc key

booth.display();

break;

} else {

cout << "Invalid input. Please try again." << endl;

return 0;

Explanation

1. The tollBooth class has two private member variables: totalCars of type unsigned int and totalCash of
type double.

2. The class includes a constructor to initialize totalCars and totalCash to 0.

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.

5. The display() member function displays the totals.

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>

using namespace std;

class time {

private:

int hours;

int minutes;

int seconds;

public:

// Constructor to initialize time to 0

time() : hours(0), minutes(0), seconds(0) {}

// Constructor to initialize time to fixed values

time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}


// Member function to display time

void display() const {

cout << setw(2) << setfill('0') << hours << ":"

<< setw(2) << setfill('0') << minutes << ":"

<< setw(2) << setfill('0') << seconds << endl;

// Member function to add two time objects

time add(const time& t) const {

int totalSeconds = (hours * 3600 + minutes * 60 + seconds) +

(t.hours * 3600 + t.minutes * 60 + t.seconds);

int newHours = totalSeconds / 3600;

int newMinutes = (totalSeconds % 3600) / 60;

int newSeconds = totalSeconds % 60;

return time(newHours, newMinutes, newSeconds);

};

int main() {

// Create two initialized time objects

const time t1(10, 30, 0);

const time t2(2, 45, 0);

// Create one uninitialized time object

time t3;

// Add the two initialized values together

t3 = t1.add(t2);
// Display the result

cout << "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.

7. Finally, we display the result using the display() member function.

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>

using namespace std;


class employee {

private:

int employeeNumber;

float compensation;

public:

// Member function to enter employee data

void enterData() {

cout << "Enter employee number: ";

cin >> employeeNumber;

cout << "Enter employee compensation: ";

cin >> compensation;

// Member function to display employee data

void displayData() const {

cout << "Employee Number: " << employeeNumber << endl;

cout << "Employee Compensation: $" << compensation << endl;

};

int main() {

const int numEmployees = 3;

employee employees[numEmployees];

// Enter data for each employee

for (int i = 0; i < numEmployees; i++) {

cout << "Enter data for Employee " << (i + 1) << ":" << endl;

employees[i].enterData();

}
// Display data for each employee

for (int i = 0; i < numEmployees; i++) {

cout << "Employee " << (i + 1) << ":" << endl;

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

12/31/02 format, and showdate(), which displays the date

Here's a C++ program that defines a date class with the specified functionality:

Code
#include <iostream>

using namespace std;

class date {

private:

int month;

int day;

int year;

public:

// Member function to enter date

void getdate() {

char slash;

cout << "Enter date (mm/dd/yy): ";

cin >> month >> slash >> day >> slash >> year;

// Member function to display date

void showdate() const {

cout << month << "/" << day << "/" << year << endl;

};

int main() {

date d;

d.getdate();

cout << "Entered date: ";

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>

using namespace std;

// Enum for employee type

enum etype { laborer, secretary, manager };


// Date class

class date {

private:

int month;

int day;

int year;

public:

// Member function to enter date

void getdate() {

char slash;

cout << "Enter date (mm/dd/yy): ";

cin >> month >> slash >> day >> slash >> year;

// Member function to display date

void showdate() const {

cout << month << "/" << day << "/" << year;

};

// Employee class

class employee {

private:

int employeeNumber;

float compensation;

date hireDate;

etype employeeType;

public:

// Member function to enter employee data


void getemploy() {

cout << "Enter employee number: ";

cin >> employeeNumber;

cout << "Enter employee compensation: ";

cin >> compensation;

hireDate.getdate();

char type;

cout << "Enter employee type (l, s, m): ";

cin >> type;

switch (type) {

case 'l':

employeeType = laborer;

break;

case 's':

employeeType = secretary;

break;

case 'm':

employeeType = manager;

break;

default:

cout << "Invalid type. Assuming laborer." << endl;

employeeType = laborer;

// Member function to display employee data

void putemploy() const {


cout << "Employee Number: " << employeeNumber << endl;

cout << "Employee Compensation: $" << compensation << endl;

cout << "Hire Date: ";

hireDate.showdate();

cout << endl;

switch (employeeType) {

case laborer:

cout << "Employee Type: Laborer" << endl;

break;

case secretary:

cout << "Employee Type: Secretary" << endl;

break;

case manager:

cout << "Employee Type: Manager" << endl;

break;

};

int main() {

const int numEmployees = 3;

employee employees[numEmployees];

// Enter data for each employee

for (int i = 0; i < numEmployees; i++) {

cout << "Enter data for Employee " << (i + 1) << ":" << endl;

employees[i].getemploy();

}
// Display data for each employee

for (int i = 0; i < numEmployees; i++) {

cout << "Employee " << (i + 1) << ":" << endl;

employees[i].putemploy();

cout << endl;

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,

England, to the international dateline in the Pacific. Latitude is measured from 0 to 90

degrees, north or south from the equator to the poles.


Create a class angle that includes three member variables: an int for degrees, a float

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

angle value in 179°59.9’ E format. Also write a three-argument constructor. Write a

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>

using namespace std;

class angle {

private:

int degrees;

float minutes;

char direction;

public:

// Constructor to initialize angle

angle(int d, float m, char dir) : degrees(d), minutes(m), direction(dir) {}

// Member function to enter angle value

void getangle() {

cout << "Enter degrees: ";


cin >> degrees;

cout << "Enter minutes: ";

cin >> minutes;

cout << "Enter direction (N, S, E, W): ";

cin >> direction;

// Member function to display angle value

void displayangle() const {

cout << degrees << "\xF8" << setprecision(1) << fixed << minutes << "\' " << direction;

};

int main() {

// Create an angle object and initialize it

angle a(149, 34.8, 'W');

// Display the initialized angle

cout << "Initialized angle: ";

a.displayangle();

cout << endl;

// Loop to enter and display angle values

while (true) {

angle userAngle(0, 0, 'N');

userAngle.getangle();

cout << "Entered angle: ";

userAngle.displayangle();

cout << endl;


char cont;

cout << "Continue? (y/n): ";

cin >> cont;

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.

5. The loop continues until the user chooses to stop.

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

number for the new object.


Add a member function that permits an object to report its own serial number. Then

write a main() program that creates three objects and queries each one about its serial

number. They should respond I am object number 2, and so on.

Here's a C++ program that defines a class with a serial number for each object:

Code

#include <iostream>

using namespace std;

class MyClass {

private:

int serialNumber;

static int objectCount; // Static member variable to count objects

public:

// Constructor to initialize serial number

MyClass() {

serialNumber = ++objectCount; // Increment object count and assign to serial number

// Member function to report serial number

void reportSerialNumber() const {

cout << "I am object number " << serialNumber << endl;

};

// Initialize static member variable

int MyClass::objectCount = 0;
int main() {

// Create three objects

MyClass obj1;

MyClass obj2;

MyClass obj3;

// Query each object about its serial number

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.

4. We define a member function reportSerialNumber() to report the serial number of an 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

each operation, ask whether the user wants to continue.

Here's a C++ program that defines a fraction class with the specified functionality:

Code

#include <iostream>

using namespace std;

class fraction {

private:

int numerator;

int denominator;

public:

// Member function to enter fraction value

void getfraction() {

char slash;

cout << "Enter fraction (numerator/denominator): ";

cin >> numerator >> slash >> denominator;

// Member function to display fraction value


void displayfraction() const {

cout << numerator << "/" << denominator;

// Member function to add two fraction values

fraction add(const fraction& f) const {

int newNumerator = numerator * f.denominator + f.numerator * denominator;

int newDenominator = denominator * f.denominator;

fraction result;

result.numerator = newNumerator;

result.denominator = newDenominator;

return result;

};

int main() {

char cont;

do {

fraction f1, f2, sum;

cout << "Enter first fraction:" << endl;

f1.getfraction();

cout << "Enter second fraction:" << endl;

f2.getfraction();

sum = f1.add(f2);

cout << "Sum: ";


f1.displayfraction();

cout << " + ";

f2.displayfraction();

cout << " = ";

sum.displayfraction();

cout << endl;

cout << "Continue? (y/n): ";

cin >> cont;

} while (cont == 'y');

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.

You might also like