starting out with c++ 2nd edition, by tony gaddis 1 chapter 7 – classes and structured data

Post on 03-Jan-2016

240 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Starting Out with C++ 2nd Edition, by Tony Gaddis

1

Chapter 7 – Classes and Structured Data

Starting Out with C++ 2nd Edition, by Tony Gaddis

2

7.1 Abstract data types

• Abstract data types (ADTs) are data types created by the programmer. ADTs have their own range (or domain) of data and their own set of operations that may be performed on them.

Starting Out with C++ 2nd Edition, by Tony Gaddis

3

Abstraction

• An abstraction is a general model of something.

Starting Out with C++ 2nd Edition, by Tony Gaddis

4

Data Types

• C++ has several primitive data types:

Table 7-1

bool int unsigned long int

char long int float

unsigned char unsigned short int double

short int unsigned int long double

Starting Out with C++ 2nd Edition, by Tony Gaddis

5

Abstract Data Types

• A data type created by the programmer– The programmer decides what values are

acceptable for the data type– The programmer decides what operations may

be performed on the data type

Starting Out with C++ 2nd Edition, by Tony Gaddis

6

7.2 Focus on Software Engineering: Combining Data into Structures

• C++ allows you to group several variables together into a single item known as a structure.

Starting Out with C++ 2nd Edition, by Tony Gaddis

7

Table 7-2

Variable Declaration

Information Held

in t e m p N u m b e r; Employee Number

c h a r n a m e [2 5 ]; Employee’s Name

f lo a t h o u rs ; Hours Worked

f lo a t p a y R a te ; Hourly Pay Rate

f lo a t g ro ssP a y ; Gross Pay

Starting Out with C++ 2nd Edition, by Tony Gaddis

8

Table 7-2 As a Structure:

struct PayRoll

{

int empNumber;

char name[25];

float hours;

float payRate;

float grossPay;

};

Starting Out with C++ 2nd Edition, by Tony Gaddis

9

Figure 7-1

empNumber

name

hours

payRate

grossPay

deptHead

Structure Variable Name

Members

Starting Out with C++ 2nd Edition, by Tony Gaddis

10

Figure 7-2

empNumbernamehourspayRategrossPay

deptHead

empNumbernamehourspayRategrossPay

foreman

empNumbernamehourspayRategrossPay

associate

Starting Out with C++ 2nd Edition, by Tony Gaddis

11

Two steps to implementing structures:

• Create the structure declaration. This establishes the tag (or name) of the structure and a list of items that are members.

• Declare variables (or instances) of the structure and use them in the program to hold data.

Starting Out with C++ 2nd Edition, by Tony Gaddis

12

7.3 Accessing Structure Members

• The dot operator (.) allows you to access structure members in a program

Starting Out with C++ 2nd Edition, by Tony Gaddis

13

Program 7-1// This program demonstrates the use of structures.

#include <iostream>using namespace std;struct PayRoll{

int empNumber; // Employee numberchar name[25]; // Employee's namefloat hours; // hours workedfloat payRate; // Hourly Payratefloat grossPay; // Gross Pay

};

Starting Out with C++ 2nd Edition, by Tony Gaddis

14

Program continuesint main(){

PayRoll employee; // Employee is a PayRoll structurecout << "Enter the employee's number: ";cin >> employee.empNumber;cout << "Enter the employee's name: ";cin.ignore(); // To skip the remaining '\n' charactercin.getline(employee.name, 25);cout << "How many hours did the employee work? ";cin >> employee.hours;cout << "What is the employee's hourly payrate? ";cin >> employee.payRate;employee.grossPay = employee.hours * employee.payRate;cout << "Here is the employee's payroll data:\n";cout << "Name: " << employee.name << endl;

Starting Out with C++ 2nd Edition, by Tony Gaddis

15

Program continues

cout << "Number: " << employee.empNumber << endl;cout << "hours worked: " << employee.hours << endl;cout << "Hourly Payrate: " << employee.payRate << endl;

cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "Gross Pay: $" << employee.grossPay << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

16

Program Output with Example input

Enter the employee's number: 489 [Enter]Enter the employee's name: Jill Smith [Enter]How many hours did the employee work? 40 [Enter]What is the employee's hourly payrate? 20 [Enter]Here is the employee's payroll data:Name: Jill SmithNumber: 489hours worked: 40Hourly Payrate: 20Gross Pay: $800.00

Starting Out with C++ 2nd Edition, by Tony Gaddis

17

Displaying a Structure

• The contents of a structure variable cannot be displayed by passing the entire variable to cout. For example, assuming employee is a PayRoll structure variable, the following statement will not work:

cout << employee << endl; //won’t work!

Starting Out with C++ 2nd Edition, by Tony Gaddis

18

Program 7-2// This program uses a structure to hold// geometric data about a circle.

#include <iostream>#include <iomanip>#include <cmath> // For the pow functionusing namespace std;

struct Circle{

float radius;float diameter;float area;

};

const float pi = 3.14159;

Starting Out with C++ 2nd Edition, by Tony Gaddis

19

Program continues

int main(){

Circle c;cout << "Enter the diameter of a circle: ";cin >> c.diameter;c.radius = c.diameter / 2;c.area = pi * pow(c.radius, 2.0);cout << "The radius and area of the circle are:\n";cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "Radius: " << c.radius << endl;cout << "area: " << c.area << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

20

Program Output with Example input

Enter the diameter of a circle: 10 [Enter]The radius and area of the circle are:Radius: 5area: 78.54

Starting Out with C++ 2nd Edition, by Tony Gaddis

21

7.4 Initializing a Structure

• The members of a structure variable may be initialized with starting values when the structure variable is declared.

struct GeoInfo

{

char cityName[30], state[3];

long population;

int distance;

};

GeoInfo location = {“Ashville”, “NC”, 50000, 28};

Starting Out with C++ 2nd Edition, by Tony Gaddis

22

7.5 Focus on Software Engineering: Nested Structures

It’s possible for a structure variable to be a member of another structure variable.

struct Costs{ float wholesale; float retail;};struct Item{ char partNum[10], description[25]; Costs pricing;};

Starting Out with C++ 2nd Edition, by Tony Gaddis

23

7.6 Structures as Function Arguments

Structure variables may be passed as arguments to functions.

Starting Out with C++ 2nd Edition, by Tony Gaddis

24

Figure 7-3

void showRect(Rectangle r){

cout << r.length << endl;cout << r.width << endl;cout << r.area << endl;

}

showRect(box);

Starting Out with C++ 2nd Edition, by Tony Gaddis

25

Program 7-3// This program demonstrates a function that accepts// a structure variable as its argument.

#include <iostream>using namespace std;struct InvItem{

int partNum; // Part numberchar description[50]; // Item descriptionint onHand; // Units on handfloat price; // Unit price

};

void showItem(InvItem); // Function prototype

Starting Out with C++ 2nd Edition, by Tony Gaddis

26

Program continuesint main(){

InvItem part = {171, "Industrial Widget", 25, 150.0};showItem(part);

return 0;}

// Definition of function showItem. This function accepts// an argument of the InvItem structure type. The contents// of the structure is displayed.

void showItem(InvItem piece){

cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "Part Number: " << piece.partNum << endl;cout << "Description: " << piece.description << endl;cout << "Units On Hand: " << piece.onHand << endl;cout << "Price: $" << piece.price << endl;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

27

Program Output

Part Number: 171 Description: Industrial Widget Units On Hand: 25 Price: $150.00

Starting Out with C++ 2nd Edition, by Tony Gaddis

28

Program 7-4// This program has a function that uses a structure

reference variable// as its parameter.#include <iostream>using namespace std;

struct InvItem{

int partNum; // Part numberchar description[50]; // Item descriptionint onHand; // Units on handfloat price; // Unit price

};

// Function Prototypesvoid getItem(InvItem&);void showItem(InvItem);

Starting Out with C++ 2nd Edition, by Tony Gaddis

29

Program continues

int main(){

InvItem part;getItem(part);showItem(part);return 0;

}

// Definition of function getItem. This function uses a// structure reference variable as its parameter. It asks the// user for information to store in the structure.

void getItem(InvItem &piece){

cout << "Enter the part number: ";cin >> piece.partNum;cout << "Enter the part description: ";cin.get(); // Eat the remaining newlinecin.getline(piece.description, 50);

Starting Out with C++ 2nd Edition, by Tony Gaddis

30

Program continues

cout << "Enter the quantity on hand: ";cin >> piece.onHand;cout << "Enter the unit price: ";cin >> piece.price;

}

// Definition of function showItem. This function accepts// an argument of the InvItem structure type. The contents// of the structure is displayed.

void showItem(InvItem piece){

cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "Part Number: " << piece.partNum << endl;cout << "Description: " << piece.description << endl;cout << "Units On Hand: " << piece.onHand << endl;cout << "Price: $" << piece.price << endl;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

31

Program Output

Enter the part number: 800 [Enter]Enter the part description: Screwdriver [Enter]Enter the quantity on hand: 135 [Enter]Enter the unit price: 1.25 [Enter]Part Number: 800Description: ScrewdriverUnits On Hand: 135Price: $1.25

Starting Out with C++ 2nd Edition, by Tony Gaddis

32

Constant Reference Parameters

• Sometimes structures can be quite large. Therefore, passing by value can decrease a program’s performance. But passing by reference can cause problems.

• Instead, pass by constant reference:

void showItem(const InvItem &piece)

{

cout.setf(ios::precision(2)|ios::fixed|ios::showpoint);

cout << “Part Number: “ << piece.partNum << endl;

cout << “Price: $” << piece.price << endl;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

33

11.8 Returning a Structure from a Function• A function may return a structure.struct Circle{ float radius, diameter, area;};

Circle getData(){ Circle temp; temp.radius = 10.0; temp.diameter = 20.0; temp.area = 314.159; return temp;}

Starting Out with C++ 2nd Edition, by Tony Gaddis

34

Program 7-5// This program uses a function to return a structure. This // is a modification of Program 11-2.#include <iostream>#include <iomanip>#include <cmath> // For the pow functionusing namespace std;

// Circle structure declaration

struct Circle{

float radius;float diameter;float area;

};

Starting Out with C++ 2nd Edition, by Tony Gaddis

35

Program continues

// Function prototypeCircle getInfo();

// Constant definition for Piconst float pi = 3.14159;

int main(){

Circle c;c = getInfo();c.area = pi * pow(c.radius, 2.0);cout << "The radius and area of the circle are:\n";cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "Radius: " << c.radius << endl;cout << "area: " << c.area << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

36

Program continues

// Definition of function getInfo. This function uses a// local variable, round, which is a Circle structure.// The user enters the diameter of the circle, which is // stored in round.diameter. The function then calculates// the radius, which is stored in round.radius. round is then// returned from the function.

Circle getInfo(){

Circle round;cout << "Enter the diameter of a circle: ";cin >> round.diameter;round.radius = round.diameter / 2;return round;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

37

Program Output with Example input

Enter the diameter of a circle: 10 [Enter]The radius and area of the circle are:Radius: 5.00area: 78.54

Starting Out with C++ 2nd Edition, by Tony Gaddis

38

7.8 Unions

• A union is like a structure, except all the members occupy the same memory area.

Figure 7-4

employee1: a PaySource union variable

1st two bytes are usedby hours, a short

All four bytes are used by sales, a float

Starting Out with C++ 2nd Edition, by Tony Gaddis

39

Program 7-6// This program demonstrates a union.#include <iostream>#include <iomanip>using namespace std;

union PaySource{

short hours;float sales;

};

int main(){

PaySource employee1;char payType;float payRate, grossPay;

Starting Out with C++ 2nd Edition, by Tony Gaddis

40

Program continues

cout.precision(2);cout.setf(ios::showpoint);cout << "This program calculates either hourly wages or\n";cout << "sales commission.\n";cout << "Enter H for hourly wages or C for commission: ";cin >> payType;

if (toupper(payType) == 'H'){

cout << "What is the hourly pay rate? ";cin >> payRate;cout << "How many hours were worked? ";cin >> employee1.hours;grossPay = employee1.hours * payRate;cout << "Gross pay: $" << grossPay << endl;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

41

Program continues

else if (payType == 'C'){

cout << "What are the total sales for this employee? ";

cin >> employee1.sales;grossPay = employee1.sales * 0.10;cout << "Gross pay: $" << grossPay << endl;

}

else{

cout << payType << " is not a valid selection.\n";}

return 0;}

Starting Out with C++ 2nd Edition, by Tony Gaddis

42

Program Output with Example input

This program calculates either hourly wages orsales commission.Enter H for hourly wages or C for commission: C [Enter]What are the total sales for this employee? 5000 [Enter]Gross pay: $500.00

Starting Out with C++ 2nd Edition, by Tony Gaddis

43

Anonymous Unions

• The members of an anonymous union have names, but the union itself has no name.

union

{

member declarations;

. . .

};

Starting Out with C++ 2nd Edition, by Tony Gaddis

44

Program 7-7// This program demonstrates an anonymous union.

#include <iostream>#include <iomanip>using namespace std;int main(){

union // Anonymous union{

short hours;float sales;

};char payType;float payRate, grossPay;

Starting Out with C++ 2nd Edition, by Tony Gaddis

45

Program continues

cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "This program calculates either hourly wages or\n";cout << "sales commission.\n";cout << "Enter H for hourly wages or C for commission: ";cin >> payType;

if (payType == 'H'){

cout << "What is the hourly pay rate? ";cin >> payRate;cout << "How many hours were worked? ";cin >> hours; // Anonymous union membergrossPay = hours * payRate;cout << "Gross pay: $" << grossPay << endl;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

46

Program continues

else if (payType == 'C'){

cout << "What are the total sales for this employee? ";

cin >> sales; // Anonymous union membergrossPay = sales * 0.10;cout << "Gross pay: $" << grossPay << endl;

}

else{

cout << payType << " is not a valid selection.\n";}return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

47

Program Output with Example input

This program calcualtes either hourly wages orsales commission.Enter H for hourly wages or C for commission: C [Enter]What are the total sales for the employee? 12000 [Enter]Gross pay: $1200.00

Starting Out with C++ 2nd Edition, by Tony Gaddis

48

7.9 Procedural and Object-Oriented Programming

• Procedural programming is a method of writing software. It is a programming practice centered on the procedures, or actions that take place in a program.

• Object-Oriented programming is centered around the object. Objects are created form abstract data types that encapsulate data and functions together.

Starting Out with C++ 2nd Edition, by Tony Gaddis

49

What’s Wrong with Procedural Programming?

• Programs with excessive global data

• Complex and convoluted programs

• Programs that are difficult to modify and extend

Starting Out with C++ 2nd Edition, by Tony Gaddis

50

What is Object-Oriented Programming?

• OOP is centered around the object, which packages together both the data and the functions that operate on the data.

Starting Out with C++ 2nd Edition, by Tony Gaddis

51

Figure 7-5 Member Variablesfloat width;float length;float area;

Member Functionsvoid setData(float w, float l){ … function code … }

void calcArea(){ … function code … }

void getWidth(){ … function code … }

void getLength(){ … function code … }

void getArea(){ … function code … }

Starting Out with C++ 2nd Edition, by Tony Gaddis

52

Terminology

• In OOP, an object’s member variables are often called its attributes and its member functions are sometimes referred to as its behaviors or methods.

Starting Out with C++ 2nd Edition, by Tony Gaddis

53

Figure 7-6

Starting Out with C++ 2nd Edition, by Tony Gaddis

54

How are Objects Used?

• Although the use of objects is only limited by the programmer’s imagination, they are commonly used to create data types that are either very specific or very general in purpose.

Starting Out with C++ 2nd Edition, by Tony Gaddis

55

General Purpose Objects

– Creating data types that are improvements on C++’s built-in data types. For example, an array object could be created that works like a regular array, but additionally provides bounds-checking.

– Creating data types that are missing from C++. For instance, an object could be designed to process currencies or dates as if they were built-in data types.

– Creating objects that perform commonly needed tasks, such as input validation and screen output in a graphical user interface.

Starting Out with C++ 2nd Edition, by Tony Gaddis

56

Application-Specific Objects

• Data types created for a specific application. For example, in an inventory program.

Starting Out with C++ 2nd Edition, by Tony Gaddis

57

7.10 Introduction to the Class

• In C++, the class is the construct primarily used to create objects.

class class-name

{

declaration statements here

};

Starting Out with C++ 2nd Edition, by Tony Gaddis

58

Example:

class Rectangle

{

private:

float width, length, area;

public:

void setData(float, float);

void calcArea();

float getWidth();

float getLength();

float getArea();

};

Starting Out with C++ 2nd Edition, by Tony Gaddis

59

Access Specifiers

• The key words private and public are access specifiers.

• private means they can only be accessed by the member functions.

• public means they can be called from statements outside the class.– Note: the default access of a class is private, but it is

still a good idea to use the private key word to explicitly declare private members. This clearly documents the access specification of the class.

Starting Out with C++ 2nd Edition, by Tony Gaddis

60

7.11 Defining Member Functions

• Class member functions are defined similarly to regular functions.

void Rectangle::setData(float w, float l)

{

width = w;

length = l;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

61

continued from previous slide

void rectangle::calcArea(){ area = width * length;

}

etc. for all remaining member functions

Starting Out with C++ 2nd Edition, by Tony Gaddis

62

7.12 Defining an Instance of a Class

• Class objects must be defined after the class is declared.

• Defining a class object is called the instantiation of a class.

Rectangle box; // box is an instance // of Rectangle

Starting Out with C++ 2nd Edition, by Tony Gaddis

63

Accessing an Object’s Members

box.setData(10.0, 12.0)

box.calcArea();

cout << box.getWidth();

cout << box.getLength();

cout << box.getArea();

Starting Out with C++ 2nd Edition, by Tony Gaddis

64

Program 7-8// This program demonstrates a simple class.#include <iostream>using namespace std;

// Rectangle class declaration.class Rectangle{

private:float width;float length;float area;

public:void setData(float, float);void calcArea();float getWidth();float getLength();float getArea();

};

Starting Out with C++ 2nd Edition, by Tony Gaddis

65

Program continues

// setData copies the argument w to private member// width andl to private member length.

void Rectangle::setData(float w, float l){

width = w;length = l;

}

// calcArea multiplies the private members width// and length. The result is stored in the private// member area.

void Rectangle::calcArea(){

area = width * length;}

Starting Out with C++ 2nd Edition, by Tony Gaddis

66

Program continues

// getWidth returns the value in the private member width.float Rectangle::getWidth(){

return width;}// getLength returns the value in the private member length.float Rectangle::getLength(){

return length;}// getArea returns the value in the private member area.float Rectangle::getArea(){

return area;}

Starting Out with C++ 2nd Edition, by Tony Gaddis

67

Program continues

int main(){

Rectangle box;float wide, boxLong;cout << "This program will calculate the area of a\n";cout << "rectangle. What is the width? ";cin >> wide;cout << "What is the length? ";cin >> boxLong;box.setData(wide, boxLong);box.calcArea();cout << "Here is the rectangle's data:\n";cout << "width: " << box.getWidth() << endl;cout << "length: " << box.getLength() << endl;cout << "area: " << box.getArea() << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

68

Program Output

This program will calculate the area of arectangle. What is the width? 10 [Enter]What is the length? 5 [Enter]Here is the rectangle's data:width: 10length: 5area: 50

Starting Out with C++ 2nd Edition, by Tony Gaddis

69

7.13 Why Have Private Members?

• In object-oriented programming, an object should protect its important data by making it private and providing a public interface to access that data.

Starting Out with C++ 2nd Edition, by Tony Gaddis

70

7.14 Focus on Software Engineering: Some Design Considerations

• Usually class declarations are stored in their own header files. Member function definitions are stored in their own .cpp files.

• The #ifndef directive allows a program to be conditionally compiled. This prevents a header file from accidentally being included more than once.

Starting Out with C++ 2nd Edition, by Tony Gaddis

71

Program 7-9Contents of rectang.h#ifndef RECTANGLE_H#define RECTANGLE_H// Rectangle class declaration.class Rectangle{

private:float width;float length;float area;

public:void setData(float, float);void calcArea();float getWidth();float getLength();float getArea();

};

#endif

Starting Out with C++ 2nd Edition, by Tony Gaddis

72

Contents of rectang.cpp#include "rectang.h"

// setData copies the argument w to private member// width and l to private member length.void Rectangle::setData(float w, float l){

width = w;length = l;

}

// calcArea multiplies the private members width // and length. The result is stored in the private// member area.void Rectangle::calcArea(){

area = width * length;}

Starting Out with C++ 2nd Edition, by Tony Gaddis

73

Program continues

// getWidth returns the value in the private member width.float Rectangle::getWidth(){

return width;}// getLength returns the value in the private member

length.float Rectangle::getLength(){

return length;}// getArea returns the value in the private member area.float Rectangle::getArea(){

return area;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

74

Program continues

Contents of the main program, pr7-9.cpp// This program demonstrates a simple class.#include <iostream>#include "rectang.h" // contains Rectangle class declarationusing namespace std;

// Don't forget to link this program with rectang.cpp!

int main(){

Rectangle box;float wide, boxLong;cout << "This program will calculate the area of a\n";cout << "rectangle. What is the width? ";cin >> wide;cout << "What is the length? ";cin >> boxLong;

Starting Out with C++ 2nd Edition, by Tony Gaddis

75

Program continues

box.setData(wide, boxLong);box.calcArea();cout << "Here rectangle's data:\n";cout << "width: " << box.getWidth() << endl;cout << "length: " << box.getLength() << endl;cout << "area: " << box.getArea() << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

76

Performing I/O in a Class Object

• Notice that the Rectangle example has no cin or cout.

• This is so anyone who writes a program that uses the Rectangle class will not be “locked into” the way the class performs input or output.

• Unless a class is specifically designed to perform I/O, operations like user input and output are best left to the person designing the application.

Starting Out with C++ 2nd Edition, by Tony Gaddis

77

Table 7-3rectang.h Contains the class definition of Rectangle. Is

included by rectang.cpp and pr7-9.cpp rectang.cpp Contains Rectangle’s member function definitions.

Is compiled to an object file such as rectang.obj. pr7-9.cpp Contains function main. It is compiled to an object

file, such as pr7-9.obj, which is linked with rectang.cpp’s object file to form an executable file.

rectang.cpp is compiled to rectang.obj pr7-9.cpp is compiled to pr7-9.obj pr7-9.obj and rectang.obj are linked to make pr7-9.exe

Starting Out with C++ 2nd Edition, by Tony Gaddis

78

7.15 Focus on Software Engineering: Using Private Member Functions

• A private member function may only be called from a function that is a member of the same object.

Starting Out with C++ 2nd Edition, by Tony Gaddis

79

Program 7-10#include <iostream>#include "rectang2.h" // contains Rectangle class declaration// Don't forget to link this program with rectang2.cpp!using namespace std;

int main(){

Rectangle box;float wide, boxLong;cout << "This program will calculate the area of a\n";cout << "rectangle. What is the width? ";cin >> wide;cout << "What is the length? ";cin >> boxLong;box.setData(wide, boxLong);cout << "Here rectangle's data:\n";cout << "width: " << box.getWidth() << endl;cout << "length: " << box.getLength() << endl;cout << "area: " << box.getArea() << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

80

Program Output

This program will calculate the area of arectangle. What is the width? 10 [Enter]What is the length? 5 [Enter]Here rectangle's data:width: 10length: 5area: 50

Starting Out with C++ 2nd Edition, by Tony Gaddis

81

13.9 Inline Member Functions

• When the body of a member function is defined inside a class declaration, it is declared inline.

Starting Out with C++ 2nd Edition, by Tony Gaddis

82

Program 7-11Contents of rectang3.h#ifndef RECTANGLE_H#define RECTANGLE_H

// Rectangle class declaration.class Rectangle{

private:float width;float length;float area;void calcArea() { area = width *

length; }

Starting Out with C++ 2nd Edition, by Tony Gaddis

83

Program continues

public:void setData(float, float); // Prototypefloat getWidth() { return width; }float getLength() { return length; }float getArea() { return area; }

};#endifContents of rectang3.cpp#include "rectang3.h"// setData copies the argument w to private member// width and l to private member length.void Rectangle::setData(float w, float l){

width = w;length = l;calcArea();

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

84

Program continues

Contents of the main program, PR7-11.CPP#include <iostream>#include "rectang3.h" // contains Rectangle class declarationusing namespace std;// Don't forget to link this program with rectang3.cpp!

int main(){

Rectangle box;float wide, boxLong;

cout << "This program will calculate the area of a\n";cout << "rectangle. What is the width? ";cin >> wide;cout << "What is the length? ";cin >> boxLong;

Starting Out with C++ 2nd Edition, by Tony Gaddis

85

Program continues

box.setData(wide, boxLong);cout << "Here rectangle's data:\n";cout << "width: " << box.getWidth() << endl;cout << "length: " << box.getLength() << endl;cout << "area: " << box.getArea() << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

86

Program Output

This program will calculate the area of arectangle. What is the width? 10 [Enter]What is the length? 5 [Enter]Here rectangle's data:width: 10length: 5area: 50

Starting Out with C++ 2nd Edition, by Tony Gaddis

87

7.17 Constructors

• A constructor is a member function that is automatically called when a class object is created.

• Constructors have the same name as the class.

• Constructors must be declared publicly.

• Constructors have no return type.

Starting Out with C++ 2nd Edition, by Tony Gaddis

88

Program 7-12// This program demonstrates a constructor.#include <iostream>using namespace std;

class Demo{public:

Demo(); // Constructor};

Demo::Demo(){

cout << "Welcome to the constructor!\n";}

Starting Out with C++ 2nd Edition, by Tony Gaddis

89

Program continues

int main(){

Demo demoObj; // Declare a Demo object;cout << "This program demonstrates an object\n";cout << "with a constructor.\n";return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

90

Program Output

Welcome to the constructor.This program demonstrates an objectwith a constructor.

Starting Out with C++ 2nd Edition, by Tony Gaddis

91

Program 7-13// This program demonstrates a constructor.#include <iostream>using namespace std;

class Demo{public:

Demo(); // Constructor};

Demo::Demo(){

cout << "Welcome to the constructor!\n";}

Starting Out with C++ 2nd Edition, by Tony Gaddis

92

Program continues

int main(){

cout << "This is displayed before the object\n";cout << "is declared.\n\n";Demo demoObj;cout << "\nThis is displayed after the object\n";cout << "is declared.\n";return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

93

Program Output

This is displayed before the objectis declared.

Welcome to the constructor.

This is displayed after the objectis declared.

Starting Out with C++ 2nd Edition, by Tony Gaddis

94

Constructor Arguments

• When a constructor does not have to accept arguments, it is called an object’s default constructor. Like regular functions, constructors may accept arguments, have default arguments, be declared inline, and be overloaded.

Starting Out with C++ 2nd Edition, by Tony Gaddis

95

7 - 18 Destructors

• A destructor is a member function that is automatically called when an object is destroyed.– Destructors have the same name as the class, preceded

by a tilde character (~)

– In the same way that a constructor is called then the object is created, the destructor is automatically called when the object is destroyed.

– In the same way that a constructor sets things up when an object is created, a destructor performs shutdown procedures when an object is destroyed.

Starting Out with C++ 2nd Edition, by Tony Gaddis

96

Program 7-14// This program demonstrates a constructor & destructor

#include <iostream>using namespace std;class Demo{public:

Demo(); // Constructor~Demo(); // Destructor

};

Demo::Demo(){

cout << "Welcome to the constructor!\n";}

Starting Out with C++ 2nd Edition, by Tony Gaddis

97

Program continues

Demo::~Demo(){

cout << "The destructor is now running.\n";}

int main(){

Demo demoObj; // Declare a Demo object;cout << "This program demonstrates an object\n";cout << "with a constructor and destructor.\n";return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

98

Program Output

Welcome to the constructor!This program demonstrates an objectwith a constructor and destructor.The destructor is now running.

Starting Out with C++ 2nd Edition, by Tony Gaddis

99

7.19 Constructors that Accept Arguments

• Information can be passed as arguments to an object’s constructor.

Starting Out with C++ 2nd Edition, by Tony Gaddis

100

Program 7-15

Contents of sale.h#ifndef SALE_H#define SALE_H

// Sale class declarationclass Sale{private:

float taxRate;float total;

public:Sale(float rate) { taxRate = rate; }void calcSale(float cost)

{ total = cost + (cost * taxRate) };float getTotal() { return total; }

};#endif

Starting Out with C++ 2nd Edition, by Tony Gaddis

101

Program continues

Contents of main program, pr7-15.cpp#include <iostream>#include "sale.h"using namespace std;int main(){

Sale cashier(0.06); // 6% sales tax ratefloat amnt;cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "Enter the amount of the sale: ";cin >> amnt;cashier.calcSale(amnt);cout << "The total of the sale is $";cout << cashier.getTotal << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

102

Program Output

Enter the amount of the sale: 125.00The total of the sale is $132.50

Starting Out with C++ 2nd Edition, by Tony Gaddis

103

Program 7-16Contents of sale2.h#ifndef SALE2_H#define SALE2_H // Sale class declarationclass Sale{private:

float taxRate;float total;

public:Sale(float rate = 0.05) { taxRate = rate; }void calcSale(float cost)

{ total = cost + (cost * taxRate) };float getTotal() { return total; }

};#endif

Starting Out with C++ 2nd Edition, by Tony Gaddis

104

Program continues

Contents of main program, pr7-16.cpp#include <iostream>#include "sale2.h"using namespace std;

int main(){

Sale Cashier1; // Use default sales tax rateSale Cashier2(0.06); // Use 6% sales tax ratefloat amnt;cout.precision(2);cout.set(ios::fixed | ios::showpoint);cout << "Enter the amount of the sale: ";cin >> amnt;Cashier1.calcSale(amnt);Cashier2.calcSale(amnt);

Starting Out with C++ 2nd Edition, by Tony Gaddis

105

Program continues

cout << "With a 0.05 sales tax rate, the total\n";cout << "of the sale is $";cout << Cashier1.getTotal() << endl;cout << "With a 0.06 sales tax rate, the total\n";cout << "of the sale is $";cout << Cashier2.getTotal() << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

106

Program Output

Enter the amount of the sale: 125.00With a 0.05 sales tax rate, the totalof the sale is $131.25With a 0.06 sales tax rate, the totalof the sale is $132.50

Starting Out with C++ 2nd Edition, by Tony Gaddis

107

7.20 Focus on Software Engineering: input Validation Objects

• This section shows how classes may be designed to validate user input.

Starting Out with C++ 2nd Edition, by Tony Gaddis

108

The toupper function

• Need to #include<cctype>• toupper accepts a single input character

and converts it to upper case.• toupper does nothing, if the input

character is already uppercase or is not a letter.

• Example: letter = toupper( ‘a’ ) assigns the value ‘A’ to letter

Starting Out with C++ 2nd Edition, by Tony Gaddis

109

The CharRange input validation class• contents of chrange.h

#ifndef CHRANGE_H#define CHRANGE_H

#include<cctype> // for toupper

class CharRange{ private: char input; //user input

char lower; //lowest valid characterchar upper; //highest valid character

public:CharRange(char, char); // constructorchar getChar();

};

#endif

Starting Out with C++ 2nd Edition, by Tony Gaddis

110

contents of chrange.cpp #include<iostream>

#include”chrange.h”

using namespace std;

CharRange::CharRange( char l, char u )

{

lower = toupper(l);

upper = toupper(u);}char CharRange::getChar()

{

for( ; ; ) //infinite loop terminated by valid input

{cin.get(input);cin.ignore();input = toupper(input);

Starting Out with C++ 2nd Edition, by Tony Gaddis

111

contents of chrange.cpp, continued if ( input < lower || input > upper )

{

cout << “Enter a value from “ << lower;

cout << “ to “ << upper << “.\n”;

}else

return input;} // end for loop

} // end getChar function definition

Starting Out with C++ 2nd Edition, by Tony Gaddis

112

Program 7-17// This program demonstrates the CharRange class.#include <iostream>#include "CHRANGE.H" // Remember to compile & link chrange.cppusing namespace std;

int main(){

// Create an object to check for characters// in the range J - N.CharRange input('J', 'N');cout << "Enter any of the characters J, K, l, M, or N.\n";cout << "Entering N will stop this program.\n";while (input.getChar() != 'N');return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

113

Program Output with Example input

Enter any of the characters J, K, l, M, or NEntering N will stop this program.jkqOnly enter J, K, l, M, or N: n [Enter]

Starting Out with C++ 2nd Edition, by Tony Gaddis

114

7.21 Overloaded Constructors

• More than one constructor may be defined for a class.

Starting Out with C++ 2nd Edition, by Tony Gaddis

115

Example:Contents of sale3.h#ifndef SALE3_H#define SALE3_Hclass Sale{private:

float taxRate, total;public:

//default constructorSale (float rate = 0.05) { taxRate = rate; } // overloaded constructorSale ( float r, float cost)

{ taxRate = r; calcSale(cost); }void calcSale(float cost) { total = cost + (cost*taxRate); }float getTotal() { return total; }

};

#endif

Starting Out with C++ 2nd Edition, by Tony Gaddis

116

Program 7-18 #include<iostream>

#include “sale3.h”using namespace std;

int main(){

//Declare Sale object with 6% sales tax calculated// on a $24.95 sale.Sale cashier(0.06, 24.95);cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << “With a 6% sales tax rate, the total\n”;cout <<“ of the $24.95 sale is $”;cout << cashier.getTotal() << endl;return 0;

}

Starting Out with C++ 2nd Edition, by Tony Gaddis

117

Program output

With a 6% sales tax rate, the totalof the $24.95 sale is $26.45

Starting Out with C++ 2nd Edition, by Tony Gaddis

118

7.22 Only One Default Constructor and one Destructor

• A class may only have one default constructor and one destructor.

• Once you declare ANY constructorfor a class, there is no longer a systemdefined default constructor for that class.

Starting Out with C++ 2nd Edition, by Tony Gaddis

119

7.24 Focus on Engineering: Object-Oriented Analysis

1. Identify the objects to be used in the program.

2. Define the objects’ attributes.

3. Define the objects’ behaviors.

4. Define the relationships between objects.

Starting Out with C++ 2nd Edition, by Tony Gaddis

120

Figure 7-7

top related