Make your own free website on Tripod.com

Tutorial 12

Classes and Objects

 The instructor’s notes for this tutorial will consist of the following:

Overview

This tutorial differentiates between procedure-oriented programming and object-oriented programming. In order to do this, the terminology used in object-oriented programming is introduced. Also, the basic components of object-oriented programming (classes and objects) are introduced and implemented in C++.

Objectives

After completing the tutorial, the student will be able to:

 

Lecture Notes

Review of programming methods

You will remember from the previous tutorials that currently the two most popular methods used to create computer programs are the procedure-oriented method and the object-oriented method. When using the procedure-oriented method to create a program, the programmer concentrates on the major tasks that the program needs to perform. A programmer using the procedure-oriented method typically assigns each major task to a function, which is the primary component of a procedure-oriented program. Note that you have been using procedure-oriented programming methods up through the first eleven tutorials.

Different from the procedure-oriented method, which focuses on the individual tasks the program must perform, the object-oriented method requires the programmer to focus on the objects that a program can use to accomplish its goal. The primary component in an object-oriented program is an object. In this tutorial, you will learn more about object-oriented programming and how to create simple object-oriented programs.

Introduction to object-oriented programming

Unlike the procedure-oriented method of programming, the object-oriented method allows the programmer to use familiar objects to solve problems. The ability to use objects that model things found in the real world makes problem solving much easier. Additionally, because each object is viewed as an independent unit, an object can be used in more than one program, usually with little or no modification. The ability to use an object for more than one purpose saves programming time and money (which is an advantage that contributes to the popularity of object-oriented programming).

In the first eleven tutorials, although you have been using the procedure-oriented method of programming, you have been using objects. The keywords cin and cout, for example, are actually the names of objects created for you by C++ (cin representing the keyboard, and cout representing the monitor). Remember also that you may use (or reuse) the cin and cout objects in any program that contains the #include <iostream> directive.

Object-oriented programming terminology

On page 421 of your textbook the author covers the various terms used in object-oriented programming. When discussing object-oriented programs, you will hear the term OOP used. OOP stands for Object-Oriented Programming, a programming methodology based on objects. An object is anything that can be seen or touched (nearly anything). Objects used in object-oriented programs can take on many forms. An object can also represent something in real life. Every object has attributes and behaviors. The attributes are the characteristics that describe the object. On the other hand, an object’s behaviors are the operations (or actions) that the object is capable of performing.

Another term used in OOP is class. A class is a pattern or blueprint for creating an object. Every object used in an object-oriented program comes from a class. A class contains (or encapsulates) all of the attributes and behaviors that describe the object the class creates. Objects created from a class are referred to as instances of the class, and are said to be instantiated from the class.

Abstraction is another term used in OOP. Abstraction refers to the hiding of the internal details of the object from the user. By hiding the internal details from the user, the user cannot inadvertently make changes to the object. Attributes and behaviors that are not hidden are exposed to the user. The idea behind abstraction is to expose to the user only those attributes and behaviors that are necessary to the object, and to hide everything else.

One final group of terms begins with inheritance. Inheritance refers to the fact that you can create one class from another class. The new class, called the derived class, inherits the attributes and behaviors of the original class, called the base class. Note that once the derived class inherits all of the attributes and behaviors of the base class, the newly created derived class can be modified.

 

Defining a class in C++

Every object used in a program is created from a class. The cin and cout objects, for example, are created from the istream and ostream classes, respectively. Each of these classes defines the attributes and behaviors of the object it creates. In addition to using objects provided to you by C++, you can also create your own objects. Before you can do so, however, you must first create the object’s class. Like the C++ classes, your classes must also specify the attributes and behaviors of the objects they create.

In C++ you create a class using a class definition. You typically enter the code for the class definition in a header file. You can then use the class to create objects in any program that contains the appropriate #include directive. In C++ a class definition contains two sections, a declaration section and an implementation section.

 

Declaration section of the class definition

The declaration section of the class definition contains the C++ class statement, which specifies the name of the class, as well as the attributes and behaviors of the class. Below is the syntax of the class statement:

class className

{

public:

public attributes (data members)

public behaviors (member functions)

private:

private attributes (data members)

private behaviors (member functions)

};

The attributes, called data members, are represented by variables within the class statement. The behaviors, called member functions, are represented by function prototypes. The members of a class can be either public or private members. You record the public members below the keyword public, while you record the private members below the keyword private.

When you use a class to create an object in a program, only the public members of the class are exposed to the program (the private members are hidden). In most cases, you expose the member functions and hide the data members. You expose the member functions to allow the program to use the service each function provides. You hide the data members to protect their contents from being changed incorrectly by the program.

See Figure 12-1 on page 423 for an example of the class statement.

 

Declaration section of the class definition

Each function listed in the declaration section must be defined in the implementation section of the class definition. An implementation section contains a definition for each function prototype listed in the declaration section. The first definition recorded in the implementation section, as well as the first prototype listed in the declaration section, pertains to the default constructor function.

See Figure 12-2 on page 425 for an example of a class statement including both the declaration and implementation sections.

 

The default constructor function

A constructor function, often called a constructor, is a member function that C++ automatically calls when you use the class to create an object. The sole purpose of the constructor is to initialize the class’s variables. Every class should have at least one constructor. Each constructor included in a class must have the same name as the class, but its formal parameters (if any) must be different from any other constructor in the class. A constructor that has no formal parameters is called the default constructor.

You list each constructor’s function prototype below the keyword public in the declaration section of the class definition, and you list its function definition in the implementation section. Unlike other function prototypes and function definitions, a constructor’s prototype and definition do not begin with a data type. This is because the sole purpose of a constructor is to initialize the class’s variables. A constructor will never return a value, so no data type (not even void) is included in the prototype or definition.

See Figure 12-2 on page 425 for an example of a constructor (Date()). Notice that the class name is separated from the constructor name with two colons (::). This is called the scope resolution operator, and it indicates which function belongs to which class.

Using a class in a program

Once a class has been defined, you can create an instance of it (an object) in a program. As mentioned earlier, you typically enter the code for a class definition in a header file. When including a C++ standard header file in a program, you enclose the header file’s name in angle brackets (example: #include <iostream>). Note that if your header file is not included in the include folder, you will set its exact location in double quotes (example: #include "c:\cpp\myclasses\date").

You call a public member function by preceding its name with the object’s name and a period. The period that separates the object name from the function name is called the dot member selection operator, and it indicates that the function is a member of the class used to create the object.

See Figure 12-3 for an example of using a class in a program.

 

List of OOP (Object-Oriented Programming) Terms

 

Solutions to Questions

1. a a class

2. d a class is considered an object

3. c private

4. c public

5. b only through the public members of the class

6. a header

7. c member functions, data members

8. c implementation

9. b #include "c:\cpp\tut12\MyClasses\userclass"

10. a :: (2 colons)

11. a animal

12. b Because the constructor function does not return a value, you place the keyword void before

the constructor’s name

13. b Animal dog;

14. a Animal::displayBreed()

 

Solutions to Concept Lesson Exercises

1.

class Employee

{

public:

Employee();

void setEmployee(string, int);

private:

string name;

int salary;

};

Employee::Employee()

{

name = "";

salary = 0;

} //end of default constructor

void Employee::setEmployee(string n, int s)

{

name = n;

salary = s;

} //end of setEmployee function

2.

class Employee

{

public:

Employee();

void setEmployee(string, int);

float getSalary();

string getName();

private:

string name;

int salary;

};

Employee::Employee()

{

name = "";

salary = 0;

} //end of default constructor

void Employee::setEmployee(string n, int s)

{

name = n;

salary = s;

} //end of setEmployee function

float Employee::getSalary()

{

return salary;

} //end of getSalary function

string Employee::getName()

{

return name;

} //end of getName function

3.

class Employee

{

public:

Employee();

void setEmployee(string, int);

float getSalary();

string getName();

void calcNewSalary(float);

private:

string name;

int salary;

};

Employee::Employee()

{

name = "";

salary = 0;

} //end of default constructor

void Employee::setEmployee(string n, int s)

{

name = n;

salary = s;

} //end of setEmployee function

float Employee::getSalary()

{

return salary ;

} //end of getSalary function

string Employee::getName()

{

return name;

} //end of getName function

void Employee::calcNewSalary(float r)

{

if (r >= 0)

salary = salary * r + salary;

else

cout << "Error" << endl;

//end if

} //end of calcNewSalary function

 

 

4.

//T12ConE04 - Employee class definition

#include <iostream>

#include <string>

using namespace std;

class Employee

{

public:

Employee();

void setEmployee(string, int);

float getSalary();

string getName();

void calcNewSalary(float);

private:

string name;

int salary;

};

Employee::Employee()

{

name = "";

salary = 0;

} //end of default constructor

void Employee::setEmployee(string n, int s)

{

name = n;

salary = s;

} //end of setEmployee function

float Employee::getSalary()

{

return salary ;

} //end of getSalary function

string Employee::getName()

{

return name ;

} //end of getName function

void Employee::calcNewSalary(float r)

{

if (r >= 0)

salary = salary * r + salary;

else

cout << "Error" << endl;

//end if

} //end of calcNewSalary function

 

//T12ConE04.cpp - displays an employee's name and salary

#include <iostream>

#include <string>

#include "c:\cpp\myclasses\T12ConE04 - Solution"

using namespace std;

int main()

{

//create object

Employee empObj;

//declare variables

string name = "";

int pay = 0;

float rate = 0.0;

//get name, salary, and raise percentage

cout << "Employee's name: ";

getline(cin, name);

cout << "Employee's salary: ";

cin >> pay;

cout << "Raise rate: ";

cin >> rate;

//assign values to object

empObj.setEmployee(name, pay);

//use object to display name and current salary

cout << empObj.getName() << endl;

cout << empObj.getSalary() << endl;

//use object to calculate new salary

empObj.calcNewSalary(rate);

//use object to display new salary

cout << empObj.getSalary() << endl;

return 0;

} //end of main function

5.

//T12ConE05 - Date class definition

#include <string>

using namespace std;

class Date

{

public:

Date();

void assignDate(string, string, string);

string getDate(string);

private:

string month;

string day;

string year;

};

Date::Date()

{

month = "";

day = "";

year = "";

} //end of default constructor

void Date::assignDate(string m, string d, string y)

{

month = m;

day = d;

year = y;

} //end of assignDate function

string Date::getDate(string separator)

{

return month + separator + day + separator + year;

} //end of getDate function

//T12ConE05.cpp - displays a formatted date

#include <iostream>

#include <string>

#include "c:\cpp\myclasses\T12ConE05 - Solution"

using namespace std;

int main()

{

//create object

Date dateObj;

//declare variables

string month = "";

string day = "";

string year = "";

string separator = "";

//get month, day, year, and separator

cout << "Month: ";

getline(cin, month);

cout << "Day: ";

getline(cin, day);

cout << "Year: ";

getline(cin, year);

cout << "Separator (/ or -): ";

getline(cin, separator);

//assign values to object

dateObj.assignDate(month, day, year);

//use object to get the formatted date

cout << dateObj.getDate(separator) << endl;

return 0;

} //end of main function

 6.

//T12ConE06 - Date class definition

#include <string>

using namespace std;

class Date

{

public:

Date();

void assignDate(string, string, string);

string getDate();

string getMonth();

string getDay();

string getYear();

private:

string month;

string day;

string year;

};

Date::Date()

{

month = "";

day = "";

year = "";

} //end of default constructor

void Date::assignDate(string m, string d, string y)

{

month = m;

day = d;

year = y;

} //end of assignDate function

string Date::getDate()

{

return month + "/" + day + "/" + year;

} //end of getDate function

string Date::getMonth()

{

return month;

} //end of getMonth function

string Date::getDay()

{

return day;

} //end of getDay function

string Date::getYear()

{

return year;

} //end of getYear function

//T12ConE06.cpp - displays the month, day, and year

#include <iostream>

#include <string>

#include "c:\cpp\myclasses\T12ConE06 - Solution"

using namespace std;

int main()

{

//create object

Date dateObj;

//declare variables

string month = "";

string day = "";

string year = "";

//get month, day, and year

cout << "Month: ";

getline(cin, month);

cout << "Day: ";

getline(cin, day);

cout << "Year: ";

getline(cin, year);

//assign values to object

dateObj.assignDate(month, day, year);

//use object to get the month

cout << "You entered month " << dateObj.getMonth() << endl;

//use object to get the day

cout << "You entered day " << dateObj.getDay() << endl;

//use object to get the year

cout << "You entered year " << dateObj.getYear() << endl;

return 0;

} //end of main function

7.

//T12ConE07 - Date class definition

#include <iostream>

using namespace std;

class Date

{

public:

Date();

int assignDate(int, int, int);

void displayDate();

private:

int month;

int day;

int year;

};

Date::Date()

{

month = 0;

day = 0;

year = 0;

} //end of default constructor

int Date::assignDate(int m, int d, int y)

{

int returnValue = 0;

month = m;

day = d;

year = y;

switch (m)

{

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12: if (d <= 0 || d > 31)

returnValue = 1;

break;

case 4:

case 6:

case 9:

case 11: if (d <= 0 || d > 30)

returnValue = 1;

break;

case 2: if (y % 4 != 0 && (d <= 0 || d > 28))

returnValue = 1;

else if (y % 4 == 0 && (d <= 0 || d > 29))

returnValue = 1;

break;

default: returnValue = 1;

}; //end switch

return returnValue;

} //end of assignDate function

 

 

void Date::displayDate()

{

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

} //end of displayDate function

 

//T12ConE07.cpp - displays a date

#include <iostream>

#include "c:\cpp\myclasses\T12ConE07 - Solution"

using namespace std;

int main()

{

//create object

Date dateObj;

//declare variables

int flag = 0;

int month = 0;

int day = 0;

int year = 0;

//get month, day, and year

cout << "Month: ";

cin >> month;

cout << "Day: ";

cin >> day;

cout << "Year: ";

cin >> year;

//assign values to object

flag = dateObj.assignDate(month, day, year);

//if the month and day values are valid, use the object

//to display the date--otherwise, display an error message

if (flag == 0)

{

dateObj.displayDate();

cout << endl;

}

else

cout << "Error in date entry" << endl;

//end if

return 0;

} //end of main function

 

8.

//My first header file

9. Changes made to the original code are shaded.

class Item

{

public:

Item();

void assignItem(string, float);

private:

string name;

float price;

};

Item::Item()

{

name = "";

price = 0.0;

} //end of default constructor

void Item::assignItem(string n, float p)

{

name = n;

price = p;

} //end of assignItem function

Solutions to Application Lesson Exercises

 

1.

//Rectangle - defines a Rectangle class

//declaration section

class Rectangle

{

public:

Rectangle();

void setDimensions(float, float);

float area();

float perimeter();

private:

float length;

float width;

};

//implementation section

Rectangle::Rectangle()

{

length = 0.0;

width = 0.0;

} //end of default constructor

void Rectangle::setDimensions(float len, float wid)

{

//assigns length and width

if (len > 0 && wid > 0)

{

length = len;

width = wid;

} //end if

} //end of setDimensions function

float Rectangle::area()

{

return length * width;

} //end of area function

float Rectangle::perimeter()

{

return (length + width) * 2;

} //end of perimeter function

 

//T12AppE01.cpp - displays the cost of a fence

#include <iostream>

#include "c:\cpp\myclasses\rectangle - solution"

using namespace std;

int main()

{

//declare rectangle object

Rectangle fenceObj;

//declare variables

float fenceLength = 0.0;

float fenceWidth = 0.0;

float pricePerFt = 0.0;

float fencePerimeter = 0.0;

float totalPrice = 0.0;

//get the length, width, and price

cout << "Enter the length, in feet: ";

cin >> fenceLength;

cout << "Enter the width, in feet: ";

cin >> fenceWidth;

cout << "Enter the price per linear foot: ";

cin >> pricePerFt;

//assign data

fenceObj.setDimensions(fenceLength, fenceWidth);

//calculate the perimeter

fencePerimeter = fenceObj.perimeter();

//calculate the total price

totalPrice = fencePerimeter * pricePerFt;

//display the perimeter and the total price

cout << fixed;

cout.precision(2);

cout << "Perimeter: " << fencePerimeter << endl;

cout << "Total price: $" << totalPrice << endl;

return 0;

} //end of main function

 2.

//T12AppE02 - defines a Rectangle class

//declaration section

class Rectangle

{

public:

Rectangle();

void setDimensions(float, float);

float area();

float perimeter();

float getLength();

float getWidth();

private:

float length;

float width;

};

//implementation section

Rectangle::Rectangle()

{

length = 0.0;

width = 0.0;

} //end of default constructor

void Rectangle::setDimensions(float len, float wid)

{

//assigns length and width

if (len > 0 && wid > 0)

{

length = len;

width = wid;

} //end if

} //end of setDimensions function

float Rectangle::area()

{

return length * width;

} //end of area function

float Rectangle::perimeter()

{

return (length + width) * 2;

} //end of perimeter function

float Rectangle::getLength()

{

return length;

} //end of getLength function

float Rectangle::getWidth()

{

return width;

} //end of getWidth function

//T12AppE02.cpp - displays the cost of laying sod

#include <iostream>

#include "c:\cpp\myclasses\t12appe02 - solution"

using namespace std;

int main()

{

//declare rectangle object

Rectangle lawnObj;

//declare variables

float lawnLength = 0.0;

float lawnWidth = 0.0;

float lawnArea = 0.0;

float priceSqYd = 0.0;

float totalPrice = 0.0;

//get the length, width, and price

cout << "Enter the length, in feet: ";

cin >> lawnLength;

cout << "Enter the width, in feet: ";

cin >> lawnWidth;

cout << "Enter the price per square yard: ";

cin >> priceSqYd;

//assign data

lawnObj.setDimensions(lawnLength, lawnWidth);

//calculate the area in square yards

lawnArea = lawnObj.area() / 9;

//calculate the total price

totalPrice = lawnArea * priceSqYd;

//display the length, width, area and the total price

cout << fixed;

cout.precision(2);

cout << "Length: " << lawnObj.getLength() << endl;

cout << "Width: " << lawnObj.getWidth() << endl;

cout << "Square yards: " << lawnArea << endl;

cout << "Total price: $" << totalPrice << endl;

return 0;

} //end of main function

3.

//Rectangle - defines a Rectangle class

//declaration section

class Rectangle

{

public:

Rectangle();

int setDimensions(float, float);

float area();

float perimeter();

private:

float length;

float width;

};

//implementation section

Rectangle::Rectangle()

{

length = 0.0;

width = 0.0;

} //end of default constructor

int Rectangle::setDimensions(float len, float wid)

{

int valid = 0;

//assigns length and width

if (len > 0 && wid > 0)

{

length = len;

width = wid;

valid = 1;

} //end if

return valid;

} //end of setDimensions function

float Rectangle::area()

{

return length * width;

} //end of area function

float Rectangle::perimeter()

{

return (length + width) * 2;

} //end of perimeter function

//T12AppE03.cpp - displays the cost of laying sod

#include <iostream>

#include "c:\cpp\myclasses\t12appe03 - solution"

using namespace std;

int main()

{

//declare rectangle object

Rectangle lawnObj;

//declare variables

float lawnLength = 0.0;

float lawnWidth = 0.0;

float lawnArea = 0.0;

float priceSqYd = 0.0;

float totalPrice = 0.0;

int dataOk = 0;

//get the length, width, and price

cout << "Enter the length, in feet: ";

cin >> lawnLength;

cout << "Enter the width, in feet: ";

cin >> lawnWidth;

cout << "Enter the price per square yard: ";

cin >> priceSqYd;

//assign data

dataOk = lawnObj.setDimensions(lawnLength, lawnWidth);

if (dataOk == 1)

{

//calculate the area in square yards

lawnArea = lawnObj.area() / 9;

//calculate the total price

totalPrice = lawnArea * priceSqYd;

//display the area and the total price

cout << fixed;

cout.precision(2);

cout << "Square yards: " << lawnArea << endl;

cout << "Total price: $" << totalPrice << endl;

}

else

cout << "Length and width must be greater than 0" << endl;

//end if

return 0;

} //end of main function

4.

//T12AppE04 - defines a Triangle class

//declaration section

class Triangle

{

public:

Triangle();

void setDimensions(float, float, float, float, float);

float area();

float perimeter();

private:

float base;

float height;

float side1;

float side2;

float side3;

};

//implementation section

Triangle::Triangle()

{

base = 0.0;

height = 0.0;

side1 = 0.0;

side2 = 0.0;

side3 = 0.0;

} //end of default constructor

void Triangle::setDimensions(float b, float h, float s1, float s2, float s3)

{

//assigns base, height, and sides

if (b > 0 && h > 0 && s1 > 0 && s2 > 0 && s3 > 0)

{

base = b;

height = h;

side1 = s1;

side2 = s2;

side3 = s3;

} //end if

} //end of setDimensions function

float Triangle::area()

{

return 1.0 / 2.0 * base * height;

} //end of area function

float Triangle::perimeter()

{

return side1 + side2 + side3;

} //end of perimeter function

//T12AppE04.cpp - displays the area and perimeter of a triangle

#include <iostream>

#include "c:\cpp\myclasses\t12appe04 - solution"

using namespace std;

int main()

{

//declare triangle object

Triangle triObj;

//declare variables

float triBase = 0.0;

float triHeight = 0.0;

float triSide1 = 0.0;

float triSide2 = 0.0;

float triSide3 = 0.0;

float triArea = 0.0;

float triPerimeter = 0.0;

//get the base, height, and side lengths

cout << "Enter the base: ";

cin >> triBase;

cout << "Enter the height: ";

cin >> triHeight;

cout << "Enter first side length: ";

cin >> triSide1;

cout << "Enter second side length: ";

cin >> triSide2;

cout << "Enter third side length: ";

cin >> triSide3;

//assign data

triObj.setDimensions(triBase, triHeight, triSide1, triSide2, triSide3);

//calculate the area

triArea = triObj.area();

//calculate the perimeter

triPerimeter = triObj.perimeter();

//display the area and the perimeter

cout << fixed;

cout.precision(2);

cout << "Area: " << triArea << endl;

cout << "Perimeter: " << triPerimeter << endl;

return 0;

} //end of main function

5.

//T12AppE05 - defines a Date class

#include <iostream>

using namespace std;

//declaration section

class Date

{

public:

Date();

void setDate(int, int, int);

void displayDate();

void updateDate();

private:

int month;

int day;

int year;

};

//implementation section

Date::Date()

{

month = 0;

day = 0;

year = 0;

} //end of default constructor

void Date::setDate(int n1,int n2, int n3)

{

month = n1;

day = n2;

year = n3;

} //end of setDate function

void Date::displayDate()

{

cout << month << '/' << day << '/' << year;

} //end of displayDate function

 void Date::updateDate()

{

switch (month)

{

case 1:

case 3:

case 5:

case 7:

case 8:

case 10: if (day < 31)

day = day + 1;

else

{

month = month + 1;

day = 1;

} //end if

break;

case 2: if (day < 28)

day = day + 1;

else

{

month = month + 1;

day = 1;

} //end if

break;

case 12: if (day < 31)

day = day + 1;

else

{

month = 1;

day = 1;

year = year + 1;

} //end if

break;

default: if (day < 30)

day = day + 1;

else

{

month = month + 1;

day = 1;

} //end if

} //end of switch

} //end of updateDate function

//T12AppE05.cpp - updates and displays a date

#include <iostream>

#include "c:\cpp\myclasses\t12appe05 - solution"

using namespace std;

int main()

{

//declare a date object

Date today;

//declare variables

int todayMonth = 0;

int todayDay = 0;

int todayYear = 0;

//get month,day, and year from user

cout << "Enter the month (1-12): ";

cin >> todayMonth;

cout << "Enter the day (1-31): ";

cin >> todayDay;

cout << "Enter the year: ";

cin >> todayYear;

//use public function member to assign values to private data members

today.setDate(todayMonth,todayDay,todayYear);

//use public function member to display values in private data members

cout << endl << "Today is ";

today.displayDate();

cout << "." << endl;

today.updateDate();

cout << "Tomorrow is ";

today.displayDate();

cout << "." << endl << endl;

return 0;

} //end of main function

6.

//T12AppE06 - defines a Name class

#include <string>

#include <algorithm>

using namespace std;

//declaration section

class Name

{

public:

Name();

string getName();

void upperCase(string);

private:

string firstLast;

};

 

//implementation section

Name::Name()

{

firstLast = "";

} //end of default constructor

string Name::getName()

{

return firstLast;

} //end of getName function

void Name::upperCase(string n)

{

transform(n.begin(), n.end(), n.begin(), toupper);

firstLast = n;

} //end of upperCase function

//T12AppE06.cpp - displays a name in uppercase

#include <iostream>

#include <string>

#include "c:\cpp\myclasses\t12appe06 - solution"

using namespace std;

int main()

{

//declare a name object

Name empName;

//declare variable

string fullName = "";

//enter name

cout << "Enter the full name: ";

getline(cin, fullName);

//convert name to uppercase

empName.upperCase(fullName);

//display converted name

cout << "Name: " << empName.getName() << endl;

return 0;

} //end of main function

7.

//T12AppE07 - defines a Name class

#include <string>

#include <algorithm>

using namespace std;

//declaration section

class Name

{

public:

Name();

string getName();

void upperCase(string);

void properCase(string);

private:

string firstLast;

};

 

//implementation section

Name::Name()

{

firstLast = "";

} //end of default constructor

string Name::getName()

{

return firstLast;

} //end of getName function

void Name::upperCase(string n)

{

transform(n.begin(), n.end(), n.begin(), toupper);

firstLast = n;

} //end of upperCase function

 

void Name::properCase(string n)

{

int location = 0;

//convert first letter in first name to uppercase

transform(n.begin(), n.begin() + 1, n.begin(), toupper);

//convert remaining letters to lowercase

transform(n.begin() + 1, n.end(), n.begin() + 1, tolower);

//convert first letter in last name to uppercase

location = n.find(" ", 0) + 1; //location of first letter in last name

transform(n.begin() + location, n.begin() + location + 1, n.begin() + location, toupper);

firstLast = n;

} //end of upperCase function

 //T12AppE07.cpp - displays a name in proper case

#include <iostream>

#include <string>

#include "c:\cpp\myclasses\t12appe07 - solution"

using namespace std;

int main()

{

//declare a name object

Name empName;

//declare variable

string fullName = "";

//enter name

cout << "Enter the full name: ";

getline(cin, fullName);

//convert name to proper case

empName.properCase(fullName);

//display converted name

cout << "Name: " << empName.getName() << endl;

return 0;

} //end of main function

8.

//Rectangle - defines a Rectangle class

//declaration section

class Rectangle

{

public:

Rectangle();

void setDimensions(float, float);

float area();

float perimeter();

private:

float length;

float width;

};

//implementation section

Rectangle::Rectangle()

{

length = 0.0;

width = 0.0;

} //end of default constructor

void Rectangle::setDimensions(float len, float wid)

{

//assigns length and width

if (len > 0 && wid > 0)

{

length = len;

width = wid;

} //end if

} //end of setDimensions function

float Rectangle::area()

{

return length * width;

} //end of area function

float Rectangle::perimeter()

{

return (length + width) * 2;

} //end of perimeter function

 //T12AppE08.cpp - displays the cost of laying sod

#include <iostream>

#include "c:\cpp\myclasses\rectangle - solution"

using namespace std;

//function prototype

void calcAndDisplay(Rectangle, float);

int main()

{

//declare rectangle object

Rectangle lawnObj;

//declare variables

float lawnLength = 0.0;

float lawnWidth = 0.0;

float priceSqYd = 0.0;

//get the length, width, and price

cout << "Enter the length, in feet: ";

cin >> lawnLength;

cout << "Enter the width, in feet: ";

cin >> lawnWidth;

cout << "Enter the price per square yard: ";

cin >> priceSqYd;

//assign data

lawnObj.setDimensions(lawnLength, lawnWidth);

calcAndDisplay(lawnObj, priceSqYd);

return 0;

} //end of main function

//*****program-defined functions*****

void calcAndDisplay(Rectangle rec, float p)

{

float lawnArea = 0.0;

float totalPrice = 0.0;

//calculate the area in square yards

lawnArea = rec.area() / 9;

//calculate the total price

totalPrice = lawnArea * p;

//display the area and the total price

cout << fixed;

cout.precision(2);

cout << "Square yards: " << lawnArea << endl;

cout << "Total price: $" << totalPrice << endl;

} //end of calcAndDisplay function

9.

//T12AppE09 - defines a Rectangle class

//declaration section

class Rectangle

{

public:

Rectangle();

void setDimensions(float, float, float);

void setDimensions(float, float);

float area();

float perimeter();

float volume();

private:

float length;

float width;

float depth;

};

//implementation section

Rectangle::Rectangle()

{

length = 0.0;

width = 0.0;

depth = 0.0;

} //end of default constructor

void Rectangle::setDimensions(float len, float wid, float dep)

{

//assigns length, width, and depth

if (len > 0 && wid > 0 && dep > 0)

{

length = len;

width = wid;

depth = dep;

} //end if

} //end of setDimensions function

void Rectangle::setDimensions(float len, float wid)

{

//assigns length and width

if (len > 0 && wid > 0)

{

length = len;

width = wid;

} //end if

} //end of setDimensions function

float Rectangle::area()

{

return length * width;

} //end of area function

float Rectangle::perimeter()

{

return (length + width) * 2;

} //end of perimeter function

 

 

float Rectangle::volume()

{

return length * width * depth;

} //end of volume function

//T12AppE09.cpp - displays the volume and number of gallons of water

#include <iostream>

#include "c:\cpp\myclasses\t12appe09 - solution"

using namespace std;

int main()

{

//declare rectangle object

Rectangle poolObj;

//declare variables

float poolLength = 0.0;

float poolWidth = 0.0;

float poolDepth = 0.0;

float poolVolume = 0.0;

float numGallons = 0.0;

//get the length, width, and depth

cout << "Enter the length, in feet: ";

cin >> poolLength;

cout << "Enter the width, in feet: ";

cin >> poolWidth;

cout << "Enter the depth, in feet: ";

cin >> poolDepth;

//assign data

poolObj.setDimensions(poolLength, poolWidth, poolDepth);

//calculate the volume

poolVolume = poolObj.volume();

//calculate the number of gallons of water

numGallons = poolVolume / .13368;

//display the volume and number of gallons of water

cout << fixed;

cout.precision(2);

cout << "Volume: " << poolVolume << endl;

cout << "Gallons of water: " << numGallons << endl;

return 0;

} //end of main function

//T12App.cpp - displays the cost of laying sod

#include <iostream>

#include "c:\cpp\myclasses\t12appe09 - solution"

using namespace std;

int main()

{

//declare rectangle object

Rectangle lawnObj;

//declare variables

float lawnLength = 0.0;

float lawnWidth = 0.0;

float lawnArea = 0.0;

float priceSqYd = 0.0;

float totalPrice = 0.0;

//get the length, width, and price

cout << "Enter the length, in feet: ";

cin >> lawnLength;

cout << "Enter the width, in feet: ";

cin >> lawnWidth;

cout << "Enter the price per square yard: ";

cin >> priceSqYd;

//assign data

lawnObj.setDimensions(lawnLength, lawnWidth);

//calculate the area in square yards

lawnArea = lawnObj.area() / 9;

//calculate the total price

totalPrice = lawnArea * priceSqYd;

//display the area and the total price

cout << fixed;

cout.precision(2);

cout << "Square yards: " << lawnArea << endl;

cout << "Total price: $" << totalPrice << endl;

return 0;

} //end of main function

10. Changes to the original code are shaded.

//T12AppE10 - defines the Inventory class

#include <string>

#include <algorithm>

using namespace std;

//declaration section

class Inventory

{

public:

Inventory();

void setItem(string, int);

string getName();

int getQuantity();

private:

string name;

int quantity;

};

 

//implementation section

Inventory::Inventory()

{

name = "";

quantity = 0;

}//end of default constructor

void Inventory::setItem(string n, int num)

{

transform(n.begin(), n.end(), n.begin(), toupper);

name = n;

if (num > 0 && num < 500)

quantity = num;

else

quantity = 0;

}//end of setItem function

string Inventory::getName()

{

return name;

}//end of getName function

int Inventory::getQuantity()

{

return quantity;

}//end of getQuantity function

Changes to the original code are shaded.

//T12AppE10.cpp - displays name and quantity

#include <iostream>

#include <string>

#include "c:\cpp\myclasses\t12appe10"

using namespace std;

int main()

{

//declare object

Inventory item;

//declare variables

string itemName = "";

int amount = 0;

cout << "Enter item name: ";

getline(cin, itemName);

cout << "Enter amount in inventory: ";

cin >> amount;

//assign and display item values

item.setItem(itemName, amount);

cout << "Name: " << item.getName() << endl;

cout << "Amount: " << item.getQuantity() << endl;

return 0;

} //end of main function