Page 1

Bismillah hir Rehman nir Raheem ------------------------------------Assalat o Wasalam o Allika Ya RasoolALLAH

Starting Out With C++ from Control Structures through Objects (6 Ed.) th

Tony Gaddis

Ch  Ch Appendixes Index

Published By: Muhammad Hassan Riaz Yousufi

To Read Online & Download:

WWW.ISSUU.COM/SHEIKHUHASSAN


az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

, 4. 1 Instance and Static Members

'4.6 14.8

Focus on Object-Oriented Design:

Class Collaborations

ss

14.3 Memberwise Assignment 14.4 Copy Constructors 14.5 Operator Overloading

Object Conversion

'4.7 Aggregation

Friends of Classes

an

, 4.2

Ri

TOPICS

Ha

Instance and Static Members

ad

CONCEPT: Each instan ce of a class has its own copi es of th e class's instance varia bles. If a membe r variable is declared s t a t ic, however, a U in stances of that class have access to that va riable. if a member fu nction is declared static, it may be called without any instances of the class being defined .

m

Instance Variables

uh a

m

Each class object (an instance of a class) has its own copy of the class's member variables. An object's member va riabl es afe separate and distinct from the member variables of other objects of the same class. For exam ple, recall that the Rectangle class discussed in Chapfer 13 has twO member variables: width and length. Suppose that we define two objects of the Rectangle class and set their width and length member var iables as shown in the follow ing code .

Rectangle boxl , box2;

M

II Set the width and length for boxl .

boxl . setWidth (5)i

boxl .setLength(lO)i 825

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 826

Chapter 14

More About Classes

us uf

i

II Set the width and length for box2. box2 . setWidth(SOO)i box2 . setLength(lOOO);

This code creares bexl and box2, which are twO distinct objects. Each has its own width and length member vanables, as illustrated in Figure 14-1.

bexlobject

box2 object width

length

10

length

500

az

5

1000

Ri

width

Yo

Figure 14-1

When the getWidth member function is called, it returns the value stored in the calling object's width member variable. For example, the following statement displays 5 500. cout «

boxl . getWidth() «

" " «

box2 .getWidth( ) «

endl;

Static Members

ss

an

In object-oriented programming. member variables such as the Rectangle class's width and length members are known as illstance variables. They are called instance variables because each instance of the class has its own copies of the variables.

m

ad

Ha

It is possible to create a member variable or member functioo that does nOt belong to any in stance of a class. Such members are known as a static member variables and static member functions. When a value is stored in a sea tic member variable, it is not stored in an instance of the class. In fact, an instance of the class doesn't even have to exist in order fo r values ro be srored in the class's staric member variables . Likewise, static member functions do not opera te on instance variables. Instead, they can operate only on static member variables. You ca n think of static member variables and sta tic member funct ions as belonging to the class instead of to an instance of the class. In this secrion, we will take a closer look at static members. First we will examine sta tic member variab les.

m

Static Member Variables

M

uh a

When a member variable is declared with [he key word s tat ic, there will be only one copy of the member variable in memory, regardless of the number of instances of the class rhar might exist. A single copy of a class's staric member variable is sha red by all instances of the class. For example, the following Tree class uses a static member variable to keep coum of the number of instances of the class that are created.

Contents of Tre e. h 2 3

1

II Tree class class Tree {

4

private :

5

static int o bjec tCount i

II Static member variable.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.1 Instance and Static Members

7 8 9

i

public: // constructor Tree() { objectCount++; }

us uf

6

II Accessor function for objectCount int getObjectCount() const { return objectCount; }

Yo

10

11 12 13

827

};

16 17 18

// Definition of the static member variable, written /1 outside the class . int Tree::objectCount = 0;

az

14 15

an

Ri

First, notice in line 5 the declaration of the sratic member va riable named objectCount: A static member variab le is created by placing rhe key word static before the variable's data type. Also notice that in line 18 we have wrinen a definition statement for the objectCount variable, and that the statement is outside the class declaration. Thi s externa l definition statement ca uses the variable to be crea ted in memory, and is required. In line 18 we have explicitly in itia lized the objectCount variable with the value o. We could have left out the in itialization because C++ automatically stores 0 in all un initialized static member variables. It is a good practice to in itial ize the va riable anyway, so it is clear to anyone reading the code that the va riable stans out with the value O.

Ha

ss

Next, look at the constructor in lines 8 and 9. In line 9 the ++ operator is Llsed to increment objectCount. Each time an instance of the Tree class is created, the constructor will be called a nd the objectCount member variable will be incremented. As a result, the objectCount member variable will contain the number of instances of the Tree class that have been created. The getObjectCount fu nction, in lines 12 and 13, returns the value in objectCount. Progra m 14-1 demonstrates this class . Program 14-1

ad

II This program demonstrates a static member variable .

iinclude <iostream> tinclude "Tree.h" using namespace stdi

5

m

1 2 3 4 6

int main(l

7

{

II Define three Tree objects. Tree oak ; Tree elm; Tree pine;

uh a

m

8 9 10 11 12 13 14

II Display the number of Tree objects we have. cout « "We have" « pine.getObjectCount() « " trees in our program!\n"; return 0;

15

M

16 17

}

Program Output

We have 3 trees in our program!

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 828

More About Classes

i

Chapter 14

us uf

The program creates three instances of the Tree class, scored in the variables oak, elm, and pine. Although there are three instances of the class, there is only one copy of the static objectCount variable. This is illustrated in Figure 14·2. Figure 14-2

Yo

objectCount variable (slatic)

az

3

pine

elm

Ri

oak

Instances of the Tree class

an

In line 14 the p rogram caUs the getObjectCount member function to retrieve the number of instances that have been created. Although the program uses the pine object to call the

member funct ion, the same va lue would be returned if any of the objects had been used. For example, all three of the following cout statements would display the same thing.

ss

"We have «oak . getObjectCount()«" trees\n" i "We have" « elm.getObjectCount() « " trees\n" ; "We have" « pine.getObjectCount() « " trees\n" i

Ha

cout « cout « cout «

A more p ractical usc of a static member variable is demonstrated in Program 14-2. The Budget class is used ro gather the budget requests foe all the divisions of a company. The

m

ad

class lIses a sta tic member, corpBudget, to hold the amount of the overall corporate blldget. When the member functio n addBudget is ca lled, its argument is added to the current contents of corpBudget. By the time the program is finished, corpBudget wi ll contain the total of all the va lues p laced there by all the Budget class objects. (T hese files are stored in the Swd cnt So urce Code Folder Chapter 14 \Budget Version 1.)

Contents of Budget. h (Version 1) tifndef BUDGET H 'define BUDGET H

m

1 2 J

uh a

4

5

M

6 7 8 9

10 11

12

II Budget class declaration class Budget { private: static doub l e corpBudget; double divisionBudget i

public: Sudget() { divisionBudget

~

II Static member II Instance member

0; }

13

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14. 1 Instance and Static Members

void addBudget(double b) { divisionBudget += b; corpBudget += b ; }

18

double getDivisionBudget() const { return divisionBudget ; }

}:

// Definition of static member variable corpBudget double Budget: : corpBudget = 0 ;

28

az

27

#endif

Ri

Prog ram 14-2

II This program demonstrates a static class me mbe r variable . 'include <iostream> 'include <iomanip> 'include "Budget.h" using namespace std;

an

4 5 6

ss

int main() { int count; // Loop counte r const int NUM_DIVISIONS = 4 ; /1 Number of divisions Budget divisions[NUM_ DIVISIONS]: // Array of Budget objects

Ha

7 8 9 10 11

Yo

double getCorpBudget() const { return corpBudget : }

25 26

1 2 3

us uf

19 20 21 22 23 24

i

14 15 16 17

12

II Get the budget req uests for each division . for (count - 0; count < NUM_DIVISIONS: count++) { double budgetAmount: cout « " Enter the budget request for division " ; cout « (count + 1) « " : " ; cin » budgetAmount: divisions[cou nt ] . addBudge t ( budgetAmount) ;

18

19 20

ad

13 14 15 16 17

}

23 24 25 26 27 28 29 30 31

/1 Display the budget requests and the corporate budget . cout « fixed « showpoint « setprecision(2 ): cout « "\nHere are the division budget requests : \n " : for (count = 0 ; count < NUM_DIVIS I ONS : count++) { cout « "\tDivision " « (count + 1) « "\t$ ": cout « divisions[countj . getDivis i onBudget ( ) « end l: } cou t « " \tTotal Budget Requests : \tS " ;

32

cout «

33 34 35

return Oi

uh a

m

m

21 22

M

829

divisions[O I. getCorpBudget() «

end1:

}

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 14-2

More About Classes

i

Chapter 14

(continued)

us uf

830

Program Output with Example Input Shown In Bold the the the the

budget budget budget budget

request request request request

for for for for

division division division division

1: 2: 3: 4:

100000 200000 300000 400000

[Enter) (Enter) (Enter] [Enter]

Yo

Enter Enter Enter Enter

Here are the division budget requests: Division 1 $ 100000 . 00 $ 200000 . 00 $ 300000.00 $ 400000 . 00

Division 4

Total Budget Requests :

1000000.00

Static Member Functions

az

Division 3

Ri

Division 2

You declare a staric member function by placing the sta t ic keyword prototype. Here is the general form:

In

[he function's

an

static RecurnType FunctionName (ParameterTypeList):

ss

A function thar is a static member of a class cannOt access any nonstatic member data in itS class. With this limitation in mind, you might wonder what purpose static member functions serve. The following twO poims are imporram for understanding their usefulness: Even though static member va riables are declared in a class, they are actually defined ou tside the class declaration. The lifetime of a class's static member variable is the lifetime of the program. This means that a class's static member variables come into existence before any instances of the class are created. A class's static member functions can be called before any instances of rhe class are created. Thi s means that a class's sta tic member functions can access the class's static member variables before any instances of the class are defined in memory. This gives you the abi lity to create very specialized serup routines for class objects.

Ha

ad

uh a

m

m

Program 14-3, a modification of Program 14-2, demonstrates this feature. It asks the user to enter the main office's budget request before any division requests are entered. The Budget class has been modified to include a static member function named mainOff ice. This function adds its argument to the static corpBudget variable, and is called before any instances of the Budget class are defined. (These files are smred in the Student Sou rce Code "Folder Chapter 14\Budget version 2.)

Contents of Budge t. h (Version 2) 1

M

2

3 4

5

iifndef BUOGET H 'define BUOGET_ H II Budget class declaration c l ass Budget

6

(

7 8 9

private : static double corpBudget i double divisionBudgeti

II Static member variable II Instance member variable

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 831

public: Budget() {divisionBudget

us uf

10 11 12

i

14.1 Instance and Static Members

O;}

13

14 15 16

void addBudget(double b) { divisionBudget += bi corpBudget += b; }

Yo

17

18 19

double getDivisionBudget() const { return divisionBudget; }

20

double getCorpBudget() canst { return corpBudget; }

23

24 25

static void mainOffice (double)i );

26

'endif

Conte nts of Budget. cpp 'include "Budget.h"

an

1 2

5 6

7 8 9 10

II Definition of corpBudget static member variable double Budget : : corpBudget = 0 ;

ss

4

//************* ** ****** ************************************* // Definition of static member functio n mainOffice. â&#x20AC;˘ // This fu nction adds the main office's budget request to * II the corpBudget variable . * //*************** ************************************** *****

Ha

3

11

12

void Budget :: mainOftice(doubl e mottice)

13

{

15

corpBudget += moffice ;

)

II This program demonstrates a static member fu nction .

tinclude <iostream> 'include <iomanip> hnclude "Budget-h" using namespace std;

m

.

m

Progra m 14-3

uh a

6

7

9 10

11

ad

14

1 2 3 4 5

II Static member function

Ri

27

az

21 22

int main ( ) {

int count ; double mainOfficeRequest ; const int NOM DIVISIONS = 4 ;

II Loop counter II Main office budget request

/1 Number of divisions

M

12

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 14-3

(continued)

us uf

13 14 15 16 17 18 19

More About Classes

i

Chapter 14

II Get the main office's budget request . II Note that no i nstances of the Budget class have been de fin e d. cout « "Enter the main office's budget request: "; cin » mainofficeRequest; Budget :: mainOffice( mainOfficeRequest)i Budget divisionS[NUM_DI VISIONSJi 1/ An array of Budget objects .

20 21 22

II Get the budget reques ts for each division . for (count - 0 ; count < NUM_DIVISIONS; count++)

23

{

Ri

29

double budgetAmount; cout « "Enter the budget request fo r d ivision "i cout« (count + 1)« " : " j cin » budgetAmount; divisions[cQuntj . addBudget(hudgetAmo unt) ;

az

24 25 26 27 28

30 31 32 33 34 35 36 37

Yo

832

)

41 42

return 0 ;

Ha

ss

an

38 39 40

II Display the budget requests and the corporate budget . cout « f ixed « showpoint « setprecision(2) i cout « "\nHere are the d ivi sion budget requests : \ n"; for (count = 0; count < NUM~D I V I SIONS ; count ++ ) { cout « "\tDivision " « (count + 1) « "\t$ "; cout « divisions[countj . getDivisionBudget() « e ndl; ) cout « " \tTotal Budget Requests : \t$ "; cout « divisions[O ). getCorpBudge t() « endl;

43

m

ad

Program Output with Example Input Shown In Bold Enter the main office' 5 budget request: 100000 (Enter] Enter the budget request f or division 1: 100000 (Enter] Enter the budget request for division 2: 200000 (Enter) Enter the budget request for division 3: 100000 (Enter] Enter the budget request for division 4: 400000 (Enter]

uh a

m

Here a re the division budget requests: Division 1 $ 100000 . 00 Division 2 $ 200000.00 Division 3 $ 300000.00 Division 4 $ 400 000.00 Total Requests (including main office) : $ 1100000 . 00

M

Notice in line 1 7 the state ment t hat ca lls the static fun ction mainO£fice: Budget :: mainOffice(amount) ;

Calls to

static member functions do nOl use the regular notation of connecting the funct ion name to an object name with the dot operator. Instead, static mem ber functions a re called by connecting the function name ro the class name with the scope resolu tion operator.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.2 Friends of Classes

i

833

us uf

NOTE: If an instance of a class with a static member fun ction exists, the sta tic member

fun ction can be called with the class object name and the dot operator, just like any other member func tion.

Yo

Friends of Classes

CONCEPT: A friend is a fu nction or class that is not a member of a class, but has access to the private members of the class.

Ri

az

Pri vate members are hidden from all parts of the program outside the class, and accessing th em requires a ca ll to a pu blic member function. Sometimes you will want to create an exception to that rule. A (riend funct ion is a functio n that is not pan of a class, but that ha s access to the class's private members. In other words, a fri end funct ion is treated as if it were a member of the class. A friend functio n can be a regular stand-alone fun ction, or it can be a member of another class. (In fa ct, an entire class can be declared a friend of another cla ss.)

Ha

ss

an

In order for a fu nction or cl ass to become a friend of another class, it muSt be declared as sllch by the class granting it access. Classes keep a " list " of their frien ds, and onJy the external fun ctions or classes whose names appear in the list are gramed access. A fu nction is declared a friend by placing the key word friend in front of a prototype of the function. H ere is the general format: fr iend ReturnType FunctionName (ParameterTypeList)

ad

In the followin g declaration of the Budget class, the addBudget function of another class, AuxiliaryOffice has been declared a friend. (This file is stored in the Srudenr Source Code Folder Chapter 14\Budget Version 3.)

Contents of Budget. h (Version 3) 'ifndef BUDGET H 'define BUDGET H iinclude "Auxil.h"

m

1 2 3

m

4

5 6

{

10 11 12

private: static double corpBudget; double divisionBudgeti public : Budget ( )

13

{ divisionBudget

uh a

7

8 9

M

II Budget class declaration class Budget

= 0;

II Static member variable

II Instance member variable

}

14

15 16 17

void addBudget(double b) { divisionBudget += b; corpBudget += b ; }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 834

i

Chapter 14 More About Classes

us uf

18

19 20 21 22 23

double getDivisionBudget() canst { return divisionBudget: }

2'

25

II Static member function

26 27 28 29 30

static void mainOffice(double);

};

31 32

'endif

Yo

double getCorpBudget() const { return corpBudget; }

II Friend function

az

friend void AuxiliaryOffice::addBudget(double, Budget &);

Contents of Auxil . h lifndef AUXIL H 'define AUXIL H

4

class Budget ;

Ha

1 2 3 5

II Aux class declaration

7

8

class AuxiliaryOffice { private :

m

9 10

1/ Forward declaration of Budget class

ad

6

ss

an

Ri

Let's assume another class, AuxiliaryOffice, represents a division's auxiliary office, perhaps in anothe r cOLIntry. The auxiliary office makes a sepa rate budget request, which must be added co the overall corporate budget. The friend declaration of the Auxiliaryoffice: : addBudget function tells the compiler that the function is to be granted access to Budget's private members. Not ice the function takes twO arguments: a double and a reference object of the Budget class. The Budget class object that is to be modified by the functio n is passed to it, by reference, as an argument. The following code shows the declarat ion of the AuxillaryOffice class. (Th is file is stO red in the Student Source Code Folder Chapter 14 \Budget version 3.)

double auxBudgeti public :

m

11 12 13

AuxiliaryOff i ce{) ( auxBudget = 0;

14

uh a

15 16

M

17 18 19

}

double getDivisionBudget ( ) canst { return auxBudget; } void addBudget(double, Budget &);

20

};

21 22

tendif

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.2 Friends of Classes

3 4

us uf

1

2

i

Contents of Auxil. cpp

835

Hnclude "Auxil.h" #include "Budget . h"

11**************************************************** *******

9

11**************************************************** * ******

6

Yo

7 B

• II Definition of member function mainOffice . II This function is declared a friend by the Budget class . • II It adds the value of argument b to the static corpBudget * • II member variable of the Budget class .

5

10 11

void AuxiliaryOffice :: addBudget{double b, Budget &div)

12 13

{

15

az

auxBudget + - b; div.corpBudget +: b i

14

}

Ri

Notice the Auxil. h file contains the following statement in line 4:

class Budget; 1/ Forward declaration of Budget class

an

T h is is a forward declaration of the Budget class. It simply tells the compiler tha t a class named Budget w ill be declared later in the p rogram. This is necessary because t he compiler will process rhe Auxil . h file before it processes the Budget class decla ration. When it is processing the Auxil . h fi le it will see t he following fu nction declaration in li ne 19: &) i

ss

void addBudget(double , Budget

Ha

The addBudget function's second parameter is a Budget reference variable. At th is poim, t he compiler ha s nOt processed the Budget class declara tion, so, w ithout the forward declar3tion, it would n't know what a Budget re ference variable is.

ad

The follow ing code shows the definition of the addBudget fUllction. (Th is file is a lso stored in the Student Source Code Folder Chapter 14 \Budget Version 3.)

Contents of Auxil. cpp 1

'include "Auxil . h" 'include "Budget . h"

m

2 3

/1**************************************************** *******

/1 Definition of member function mainOf f ice . * /1 This function is declared a friend by the Budget class. * // It adds the value of argument b to the static corpBudget * II member variable of the Budget class. * //**************************************************** *******

uh a

m

4

5 6 7 8

M

9

10 11

void AuxiliaryOffice :: addBudget(double b , Budget &div}

12

{

13 14 15

auxBudget +: b ; div . corpBudget += hi

}

T he parameter div, a reference to a Budget class object, is used in line 14. Th is statemen t adds the parameter b ro div . corpBudget. Program .14-4 demonstrates rhe classes.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 836

More About Classes

i

Chapter 14

1

II This program demonstrates a static member fu nction .

2 3 4 5

#include <iostream> 'include <iomanip> #include "8udget.h" using namespace std ;

7

Yo

6

lnt main()

a { int count;

9 10 11

double mainofficeRequesti canst int NUM DIVISIONS

= 4;

/1 Loop counter /1 Ma in office budget reques t /1 Number of divisions

az

12

II Get the main office's budget request .

15

cout « "Enter the main office's budget request: "; ein » mainOfficeRequest;

16

Budget : :mainOffice(mainOff iceRequest);

Ri

13 14

17 18 19 20 21

us uf

Program 14·4

Budget divisionS[NUM_D I VISIONSJ; II Arr ay of Budget objects Auxiliaryoffice auxoffices[4]; 1/ Array of AuxiliaryOffice

{

double budgetAmount;

26

ss

24 25

an

II Get the budget requests for each division /1 and t hei r auxiliary offices. for (count: OJ count < NUM_DIVISIONS; count+ + )

22 23

II To hold input

II Get the request for the division office. cou t « "Enter the budget request for div ision "; cout « (count + 1) « " : "; cin » budgetAmount; divisions[countJ.addBudget(budgetAmountli

Ha

27 28 29

30 31 32

33

II Get the request for the auxiliary o ff ice . cout « "Enter the budget request for that division's\n" ; cout « "auxi liary office : " i cin » budgetAmount; auxOffices[cou nt j .addBudget(budgetAmount, div isions [countj);

35 36 37 3B

)

39 40

m

ad

3.

II Display the budget requests and the corporate budget. cout « fixed « showpoint « setprecision(2); cout « "\nHere are the division budget requests : \n" ; for (count : 0; count < NUM_DIVISIONS; count++)

44

{

uh a

m

41 42 43

cout cout cout cout

45 46 47

48 49 50 51 52

«

« «

"\tDivision " « (count + 1) « "\t\t$"; divisions(countJ.getDiv i sionBudget() « end1; "\tAuxiliary office:\t$" ; auxOffices{count].getDivisionBudget() «endl «

) cout « "Total Budget Requests:\t$ " ; cout « divisions[O].getCorpBudget() « return OJ

M 53

«

endl;

e nd1;

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 837

i

14.2 Friends of Classes

us uf

Program Output with Example Input Shown In Bold Enter the main office's budget request: 100000 [Enter] Enter the budget request for division 1: 100000 [Enter] Enter the budget request for that division's auxiliary office: SOOOO [Enter] Enter the budget request f o r divis ion 2: 200000 (Enter]

az

office: 40000 [Enter] budget request for d i v i s i on 3: JOOOOO[Enter] budget request for that division's office: 70000 [Enter] budget request for divis ion 4: 400000 [Enter] budget request for that division's off ice : 65000 [Enter]

Division 1

$100000 . 00 $50000.00

Div ision 2 Auxiliary office:

$200000.0 0

Di vi s i on 3 Auxil iar y office :

$300000. 0 0 $70000.00

Divis ion 4 Auxil i ary off i ce:

$400000.00 $65000.00

ss

an

$40000.00

Ha

Total Budget Requests:

Ri

Here are the division budget requests: Auxiliar y offi ce:

Yo

Enter the budget request for that division's auxiliary Enter the Enter the auxiliary Enter the Enter the auxiliary

$ 1325000.00

ad

As mentioned before, it is possible to make an entire class a fr iend o f a nother class. The Budget class could make the Auxili a r yOff i ce class its fri end wit h the fo llowing decla ration: fr i end c lass Aux i liaryOff i c e ;

m

m

Th is ma y no t be a good id ea, however. Every mem ber fu nction o f Aux iliaryOff i c e (including o nes t hat may be added late r) would have access to the private mem bers of Budge t . The best practice is to decla re a s fr iend s on ly those functio ns t hat must have access to the p rivate members o f the class.

~ Checkpoint What is t he difference between a n instance member varia ble a nd a static member va riable?

14.2

Static member varia bles are declared inside the class declaration . Where a re static mem ber variab les defin ed ? Does a smric member varia ble co me into existence in memory befo re, a t t he same time as, or after any instances o f its class?

uh a

14.1

M

-14. 3

14.4

What limitation does a static member functio n have?

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH More About Classes

i

Chapter 14

What action is possible with a stacic mem ber function that isn't possible with a n instance member function?

14.6

If class x declares fun ction f as a friend, does fu nction f become a member of class x?

14.7

Class Y is a friend of class x, which means [he member funcrions of class y have access to the private members of class x. Does the friend key word appear in class y'S declaration or in class x's declaration?

us uf

14.5

Yo

838

az

Memberwise Assignment

Ri

CONCEPT: The = operator may be llsed to assign one object's data to anOlher object, or to initialize one object with anot her object'S data. By default, each member of one object is copied to its coumerpart in tbe other object,

an

Like other variables (except arrays), objects may be assigned to onc another using the = operator. As an example, consider Program 14-5 wh ich uses the Rectangle class (version 4) that we disc ussed in Chapter 13 . R ecall that [he Rectangle class has rwo member vari ables: width and length. T he constructOr accepts two arguments, o ne foc width and one fo r length.

4 5

6 7

, 8

10

II This program demonstrates memberwise assignment . 'include <iostream> hnclude MRectangle . h " usi ng names pace std;

Ha

2 3

i nt main() { II Define two Rectangle objects. Rectangle boxl(lO . O, 10 . 0)1 II width - 10 . 0, l ength - 10 . 0 Rectangle box2 (20 . 0 , 20.0); II width 20 . 0, length 20 . 0

ad

1

ss

Program 14-5

m

11

12

II Displ ay each object'S width a nd length . cout « "boxl ' s width and length: " « box1.getWidth() « " " «boxl . getLength() «endl; cout « "hox2's width and length: " « box2.getWidth() « " « box2.getLength() « endl « end1;

m

13 14 15 16 17

II Assign the members o f boxl to box2. box2 c boxl;

uh a

18

19 20

21

II Display each object'S width and length again. cout« "boxl's width and length : " «boxl . getWidth() « " " « boxl . getLength() « e ndl; COU!. « "boxZ' 5 width and length : " « box2 . getWidth() « " « box2 .getLength() « end l ;

M

22 23 24 25 26 27 28

re turn 0 ; }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH ' 4.4 Copy Constructors

i

839

us uf

Program Output

boxl ' s width and length: 10 10 box2 ' s width and length: 20 20

Yo

boxl's width and length: 10 10 box2 ' s width and length: 10 10

T he following statement, which appears in line 19, copies the width and length member variables of boxl dir ectly into the width and length member variables of box2: box2 :: boxl; Memb~~wise

az

assignment also occu rs when one object is initialized with another object's the difference between assignment a nd initialization: assignmem occurs between two objects that already exist, a nd initialization happens to an object be ing created. Consider the following code;) I I Define boxl. Rectangle boxl(lOO.O, 50.0);

Ri

values.~eme m be r

an

II Define box2, initialize with boxl's values Rectangle box2 ~ boxl ;

Ha

ss

T he last statement defines a Rectangle obj ect, box2, and initializes it to the va lues stored in box!. Because memberwise assignment takes place, the box2 object will contain the exact same values as the boxl object.

Copy Constructors

ad

CONCEPT: A copy constructor is a special constructor tha t is callf'! d whenever a new object is created and initialized with another object's data.

m

m

Most of the time, the default memberwise assignment behav ior in C++ is perfectly acceptable. There are instances, however, where memberwise assignment cannot be used. For example, consider the fo llowing class. (This file is stOred in the Student Source Code Folder Chapter 14\Personlnfo Version 1.)

Contents of Personlnfo . h (Version 1)

uh a

1

finclude <cstring>

2

M

3

class Personlnfo

4

{

5 6 7

private: char *name; int age;

a

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

public: PersonInfo(char *n , int a)

{ name = new char[strlen(n) strcpy(name, nJ : age " a; }

11 12 13 14

15

+

I Ii

-Pe rsonlnfo() { delete [J name; }

16 17 18

canst char *ge tName()

19

{ return name;

20

int getAge() { return age ; }

az

21 22 23

us uf

9 10

More About Classes

Yo

Chapter 14

840

};

Ri

A potentia l problem with this class lies in the fact that one of its members, name, IS a pointer. The constructor performs a critical opera tion with the pointer: it dynamically allocates a section of memory and copies a stri ng to it. For instance, the following statement creates :I person Info object named personl, whose n<lm@ member references dynamically allocated memory holding the string "Maria Jones-Tucker":

This is depicted in Figure 14路3.

ss

Figure 14路3

an

Personlnfo personl("Maria Jones -Tucker", 25);

Name

Ha

IMaria Jones-Tucker

Pointer

Dynamically allocated memory

ad

Consider what happens when another Pe rson Info object is created and initiali zed with the personl ohjen, as in the following statement: =

personl;

m

PersonInfo person2

uh a

m

In the statement above, person2's constructor isn't called. Instead, memberwise assignment takes place, copying each of personl's member variabl es into person2. This means that a separate section of memory is not allocated for pen~on2's nome member. It simply gets a copy of the address stored in personl's name member. Both poimers will point to the same address, as depicted in Figu re 14-4.

M

In this situati on, either ObjCCl can ma n ipulare thc sU'ing, causing thc cha n ges to show up in the other object. Likewise, one object can be destroyed, causing its destructor to be called, which frees the allocated memory. The remaini ng object's name pointer would stil l reference this section of memory, although it shou ld no longer be used.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m

m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 14

More About Classes

i

842

us uf

FersOnl nfo(const PersonInEo &obj)

= new char[strlen(obj . name) + 1) ; strcpy(name, obj . name); age = obj . age; }

{ name

Yo

T he canst key word ensures that the funct ion cannOt change (he contents of the parameter. This will prevent you from inadvecrendy writing code that corrupts data.

The complete listing for the revised PersonInfo class is sho wn here. (This file is stored in the Student Source Code Folder Chapter 14 \PersonInfo Version 2,)

1 2

'include <cstring>

,3

class PersonInfo { private :

6

char *name:

7

int age;

Ri

5

az

Contents of Personlnfo. h (Version 2)

8

9

public:

II Constructor personlnfo(char *0, int a) { name = new char(strlen(n) + 1]: strcpy(name, oj ; age = a; }

ss

an

10 11 12 13 14 15

1/ Copy constructor Personlnfo{const Personlnfo &Obj) { name - new char[str1en ( obj.name) + 1); strcpy{name, obj . name); age = obj . age; }

Ha

16 17 18 19

20 21 22

ad

-persOnlnfo() { delete f] name; }

23 24 25

const char *getName()

m

26

{ return name;

27

28

m

2'

};

uh a

30

int getAge() { return age; }

M

Copy Constructors and Function Parameters When a class object is passed by val ue as an argument to a function, it is passed to a parameter that is also a class object, and the copy constructor of the function's parameter is called. Remember that when a nonreference class object is used as a function parameter it is created when the function is called, and it is initialized with the argument's value. This is why C++ requires the parameter of a copy conStructor to be a reference object. If an object were passed to the copy constructor by value, the copy constructor would create a copy of the argument and store it in the parameter object. When the parameter object is

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.5 Operator Overloading

i

843

us uf

created, irs copy constructor wi!! be called, rhus causing another parameter object to be created. T his process will continue indefinitely (or at least until the available memory fills up, ca using the program to hale).

Yo

To prcvcm rhe copy consrrucror from calling itself an infinite number of times, C++ requires its parameter to be a reference object.

The Default Copy Constructor

Checkpoint

Briefl y descr ibe wha t is meant by memberwise assignment.

14.9 14.11

Describe two instances when mem berwlse assignment occ urs . Describe a situation in which memberwisc assignment should nor be used. When is a copy constructor called?

14.12

How does rhe compiler know tha r a member function is a copy constructor?

14.13

What action is performed by a class's default copy constructor?

ss

14.10

Ri

14 .8

an

~

az

Although you may not realize it, yo u have seen the action of a copy constructor before. If a class doesn't have a copy constructor, C++ creates a default copy constructor for it. T he default copy constructor performs the memberwise assignment discussed in the previous section.

CONCEPT:

Ha

Operator Overloading

c++ allows yo u to redefin e how standard operators work when used with class objects.

c++

ad

m

m

Opera lor

Overloading

provides many operators to manipulate data of the pr imitive data types . However, what if you wish to use an operator to manipulate class objects? For example, ass ume that a class named Date exists, an d objects of the Date class hold the month, day, and year in member variables. Suppose the Date class has a member fu nction named add . The add member funct ion adds a number of days co the date, and adjusts the member variables if the dare goes to another month or yea r. For example, the following statement adds five days to the date stored in the today object: today . add ( 5) i

uh a

Although it might be obvious that the statement is adding five days to the date stored in the lise of an operator might be mo re inrui tive. For example, look at [he following statement: today,

M

today += 5 ;

This statement uses the standa rd +; operator to add 5 to today . This behavior does not happen automatically, however. The += operator mUSt be overloaded for this action to occur. In th is section, you will learn to overload many of C++ 's operators to perform specialized opera tions on class objects.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 14

More About Classes

NOTE: You have already experienced the behavior of an ove rloaded operator. The I operaror performs two types of division: floating poinr and integer. If one of the I operator's operand s is a floating point type, the result will be a floating point va lue. If both of the I operator's operands ace integers, however, a different behavior occurs: the result is an integer a nd any fra ctional parr is thrown away.

Yo

()

us uf

i

844

Overloading the = Operator

person2

=

az

Although copy constructors solve the initialization problems Inherent with objects COil ' taining poimer members, rhey do not work with simple assignment statements. Copy constructors are just rhar-consrrucrors. They are onl y invoked when an object is created. Statements like the following still perform memberwise assignment:

personl;

Ri

In order co change the way the assignmen t operator works, it must be overloaded. Operacor overloading permits you co redefine an existing opera cor's behavior when used with a class object}

an

C++ allows a class CO have specia l member functions called operator (unctions.lf you wish to redefine the way a pa rticular operato r works with an object, you define a function for

Ha

ss

that operator. The Operator function is then executed any time the opetator is Llsed with an object of that class. For example, the following version of the Personlnfo class overloads the =operaror. (This file is stored in the Student Source Code Folder Chapter 14 \ Person Info Version 3.)

Contents of Personlnfo. h (Version 3) 1 2

jinclude <cstring>

3 4

C!ClSS

5

private: char *namei int agei

ad

m

6 7 8 9 10 11

Person Info

(

m

public : II Constructor

uh a

12 13 14

persOnlnfo(char *n , int a) { name

E

new char[strlen(n) + IJ i

strcpy (name , n); age=ai}

l5

16 17

18

M

19

20 21 22

23 24

II Copy Constructor Personlnfo(const PersonInfo &obj) { name

~

new char(strlen(obj.n a me) + 1];

strcpy(name, obj.name)i age = obj.agej } II Destructor -Personlnfo( ) { delete I I name i

}

25

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH '4.5 Operator Overloading

28 29 30

int getAge() { return age; }

31 32 33 34

Yo

II Overloaded = operator void operator:(const PersonInfo &right) { delete I] name; name = new charlstrlen(right.narne) + 1]; strcpy(name, right.name); age: right.age ; }

35 36

37

38 };

az

39

i

II Accessor functions const char *getName() { return name;

us uf

26 27

845

Return type

I

Ri

Let's exam ine the operator funnion to undersmnd how it works. First look at the function header: Parameter for object on the right side of operator

Function name

I

I

an

void operator=(const Person Info &right)

ss

The name of the function is operator=. This spec ifies that the function overloads the = operato r. Beca use it is a member of the Person Info class, th is function will be called only when an assignment sta tement executes where the object on the left side of the = operator is a Person Info object.

void operator

Ha

()

NOTE: You can, if you choose, put spaces around the operatOr symbol. For instance, the functio n header above could also read: L -_ _ _ __ __ __ _ _ __ __ __ _ _ __ __ __ _ _ _ _ __ __ __ _ _ _ _ _ _ _ ~

~

(const PersonInio &right)

ad

The fu nction has one parameter: a constant reference object named right. This parameter references the object on the right side of the opera tor. For exa mple, when the statement below is executed, right will reference the person1 object:

m

person2 = personl;

m

It is not required that the parameter of .an operator function be a reference object. The Person Info example declares right as a canst refer ence for the follow ing reasons:

uh a

â&#x20AC;˘

M

â&#x20AC;˘

It was declared as a reference for efficiency purposes. T his prevents the compi ler from making a copy of the object being passed Into the function. It was declared constant so the function will not accidenrally change the comems of the argumenr.

NOTE: In the example, the parameter wa s named right simply to iJiustrate that it references the object on the right side of the operator. You can name the parameter anything you wish. Ie will always take the object on the operator's right as ies argumenr.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 14 More About Classes

i

846

persan2

= personl ;

person2 . operator~(personl);

us uf

In learnmg the mechanics of operator overloading, it is helpful to know that the following [wo statements do the same thing: II Call operator= function II Cal l operator= function

Yo

In the last statemeJ1t you can see exactly what is going on in the function call. T he personl object is being passed to the function's parameter, right. Inside the function, the values in right'S members are used to iOitialLze person2. Notice tha t the operator= function has access to the right parameter's private members. Because the operator= fu nction is a member of the Person Info class, it has access to the private members of any

az

Persanlnfo object that is passed into it.

NOTE: C++ allows operator functions to be called with regular function call notation, or by using the operator symbol. ~--------------------~

Ri

()

Program 14-6 demonstrates the Person Info class with its overloaded assignment operator. (This file is stored in the Stlldent Source Code Folde r Chapter 14 \PersonInfo Version 3.)

4 5 6

7

int main()

8

{

10

11 12 13

II create and initialize the jim object. PersonInfo j i m( "J i m Young", 27) ;

ad

9

II Create and initialize the bob object . Personlnfo bob( "Bob Faraday", 32);

14

IS 19

20

II Display the contents of the jim object. cout « "The j im Object contains: " « jim . getName() ; cout « ", " « jim .getAge( ) « endl;

uh a

21

m

17

II Crea t e the clone o b ject and initialize with jim . Personlnfo clone = jim;

m

15 16

operator .

ss

3

II This program demonstrates the overloaded #include <iostream> 'include <cstring> iinclude "PersonInfo.h" using names pace std;

Ha

1 .?

an

Program 14-6

22

23 24

II Display the contents of th e bob object . cout « "The bob Object contains : " « bob.getName(); cout « ". .. « bob. getAge () « endl;

25

M

26 27 2S 29

II Di splay the contents of the clone object. cout « "The clone Object con tains : " « c!one . getName()i cout « .. , " « clone.getAge() « endl « endl;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.5 Operator Overloading

33

clone - bob ;

II Call overloaded: operator

34

bob

II Call overloaded

jim:

=

~

i

II Assign bob to c l one . cout « "Now the clone will change to bob and "i cout « "bob will change to jim. \n\n" i

us uf

30 31 32

operator

35

II Disploy the contents of the jim object .

37

cout« cout «

38 3'

Yo

3.

847

jim.getName()i

"The jim Object contains: " « ", " « jim . getAge() « endl ;

43 44

II Display the contents of the clone object.

45 4.

cout « cout «

47 48 4.

return 0;

az

II Display the contents of the bob object . cout « "The bob Object contains : " « bob. getName ( )i cout « ", " « bob . getAge () « endl ;

40 41 42

Ri

"The clone Object contains: " «clone.getName(); ", " « clone.getAge() « endl ;

)

an

Program Output The jim Object contains : Jim Young, 27

The bob Object contains : Bob Faraday, 32

ss

The clone Object contains : Jim Young , 27

Now the clone will change to bob and bob wi l l change to j i m.

Ha

~he jim Object contains : Jim You ng , 27 The bob Object contains : Jim Young, 27 The clone Object contains : Bob Faraday , 32

ad

The = Operator's Return Value

m

There is only one problem with the ove rl oaded = operator shown in Program 14-6: it has a void rerurn type. C++'s built-in =operator allows multiple assignment statements such as: a = b = c;

uh a

m

In rhis statement, the expression b = c causes c to be assigned to b and then returns the value of c. T he rerurn value is chen stored in a. If a class objecr's overloaded =operator is to function this way, it too must have a valid rerum type. For example, the Person Info class's operator'" function could be written as:

M

canst Personlnfo operator={const Personlnfo &right) { delete IJ name ; name = new charlstrlen(right . name ) + 1J; strcpy(name, right . name); age = right_age;

return *this; )

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 848

More About Classes

i

Chapter 14

us uf

The data type of the operatOr function specifies that a canst Pe rsonlnfo object is returned. Look at the last statement in the function: return *this ;

Yo

This statement returns the value of a dereferenced poi nter: this. But what is this? Read on.

The this Pointer

T he this poimer is a special built-in po inter tha t is ava ilable to a class's mem ber functions. It a lways po ints to the instance of the cl ass mak ing the fu nctio n call. For example, if

personl and person2 are borh Pe rson Info objects, the followi ng sta tement causes the cout«

az

getName fu nction to operate on p e r sonl :

personl.getName() «endl;

cout «

person2 . getName ( ) «

endl ;

Ri

Likewise, the following statement causes getName to operate on person2:

an

When getName is operati ng on person 1, the this pointe r is pointi ng to personl. When getName is operating on person2, this is poi nting to person2. T he this poi nter a lways points to the object tha t is being used to call the member function .

NOTE : T he this pointer is passed as a hidden argument to all nonstatic member

ss

( ) L-_fu_n_c_t_io_n_'_ " __________________________________________________________-'

Ha

The overloaded - operator function is demonstrated in Progra m 14·7. T he multip le assignment statement in li ne 20 causes the opera t or'" function to execute. (T h is file and t he revised version of the PersonI nfo class is stored in t he Student Sou rce Code Folder Chapter 14 \Personlnfo Vers i on 4.)

1 2

ad

Program 14-7 II This program demonstrates the overloaded - opera t or II with a r eturn value .

'include <iostream>

4 5 6

'includ e <cstring> 'inc l ude "PersonIn f o . h" using names pace std ;

7

m

m

3

8

int main()

9

(

II Create and i n itialize the jim object_ Person Info jim{"Jim Young", 27) ;

uh a

10

11 12

13 14

II Create and in i tialize t he bob object . Per son lnfo bob( "Bob Farad ay", 32) ;

M

15

16 17

II Create the clone object and initialize with jim . Pe rsonI nfo c lone = jim;

18

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.5 Operator Overloading

i

1/ Call overloaded '" operator

clone'" bob = jim;

II Display the contents of the jim object. "The jim Object contains ; " « jim . getName();

cout « cout «

23 24

", " «

jim.getAge{) «

endl;

25 cout «

28

29 30 31

II Display the contents of the clone Object.

33 34

"The clone Object contains: " « ", " « clone. getAge () « endl;

clone.getName();

return 0;

Ri

}

az

cout « cout «

32

35

Yo

II Display the contents of the bob object. "The bob Object contains : " « bob . getName(); cout « ", " « bob .getAge() « endl:

26 27

us uf

/1 ASSign jim to bob and clone .

19 20 21 22

849

an

Program Output The jim Object contains: Jim Young, 27 The bob Object contains: Jim Young, 27 The clone Object contains: Jim Young , 27

ss

Some General Issues of Operator Overloading

Ha

Now that you have had a taste of operator overloading, let's look at some of the genera! issues involved in this programming technique. Although it is nor a good programming practice, YO ll can change an operator's entire meaning if that's what yo u wish to do. There is nothing to prevent you from changing the :::. symbol from an assignment operator to a "display" operatOr. For instance, [he fo llowing class docs just that:

ad

class Weird

m

private: int value; public : Weird{int v)

m

{value'" v; } void operator- (const weird &right)

{ cout «

right. value «

endl; }

uh a

} ;

M

Although the operator'" function in the weird class overloads the assignment operator, the function doesn't perform an assign ment. Instead, it displays the contents of right . value. Consider the foHowing program segment: Weird a(5), b(lO); b;

a

=

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 850

More About Classes

i

Chapter 14

us uf

Although the sta tement a .. b looks like an assignment statemenr, it actually causes the contents of b's value member ro be displayed on the screen:

10

Anotber operator overloading issue is that you cannOt change the number of operands taken by an operaror. The = symbol must always be a binary operator. Likewise, ++ and

Yo

-- must always be unary operators.

The last issue is that although you may overload most of the C++ operators, you cannot overload all of them. Table 14-1 shows all of the C++ operators that may be overloaded.

>

«'" ( )

~

••

•f-

,-

!=

<-

>-

&&

new

delete

f

--+-

( )

&

'-II

&-

I-

++

«

<

»

->.

»=:: ->

Ri

+

az

Table 14 -1

NOTE : Some of the operators in Table 14-1 are beyond the scope of this book and are

an

~ L-_n_ o_ t_ co_v_e_t_ ed_.________________________________________________________--" The only operators that cannOt be overloaded are

sizeof

ss

?:

Ha

Overloading Math Operators

ad

Many classes would benefit not only from an overloaded assignmenr operator, bur also from overloaded math operators. To illustrate this, consider the Fee tInches class shown in the following two files. (These files are scored in the Sru dent Source Code Folder Chapter 14 \Feet lnches Version 1.)

Contents of Feetlnches . h (Version 1) 1

iifndef FEETINCHES H 'define FEETINCHES H

m

2 3 4

/1 The FeetInches class holds distances or measurements // expressed in feet and inches .

m

5 6

uh a

7

8 9

M

10 11

12 13 14 15

16 17 18

class FeetInches private : iot feet; 1/ To hold a number of feet int inches; // To hold a number of inches voi d simplify(); // Defined in Feetlnches.cpp publ i c : II Constructor Feetlnches(int f = 0, int i = 0)

{ feet

=

f;

inches = i; simplify(); }

19

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.5 Operator Overloading

22

{ feet

23 24

= fi

i

II Mutator functions void setFeet{int f)

21

us uf

20

}

26 27

Yo

void setInches(int i) { inches = i; simplify(); }

25

II Accessor functions l ot getFeet() const { return feet ; }

28 29 30

31 32

az

int getlnches() const ( return inches; )

33 34 35

37 36

Ri

II Overloaded operator functions Feetlnches operator + (canst Feetlnches &); Feetlnches operator - (COnst FeetInches &);

36 };

39 'endif

II Overl oaded II Overloaded

+

an

40

8 51

Contents of Feetlnches. cpp (Version 1)

3

II Implementation file for the Feetlnches class 'include <cstdlib> II Needed for abs() tinclude "Feetlnches.h"

ss

1

2 4

7 8 9 10

11

void Feetlnches::simpl ify()

m

12 13 14 15 16 17 18

1/**************************************************** ******** II Definition of member function simplify . This function • II checks for values in the inches member greater than • II twelve or less than zero. If such a value is found, • II the numbers in feet and i nches are adjus t ed to conform • II to a standard feet & inches expression . For example, • II 3 feet 14 inches would be adjusted to 4 feet 2 inches and * II 5 feet -2 inches would be adjusted to 4 feet 10 inches. • 11*************************************************** * ********

Ha

6

ad

5

m

{

if (i nches >E 12) {

feet +; (inches I 12): inches - inches % 12:

19

uh a

20 21 22 23 24

) else if (inches < 0) {

feet -= «abs(inches) I 12) + 1); inches = 12 - (abS(inches) , 12);

M

25 26 27

)

28

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

32 33 34

1/************************·**************······· II Overloaded binary + operator . •

11·······********·*****·········*········***·***

Feet lnches Feetlnches::operator + (canst Feetlnches &right) {

35

Feetlnches tempi

36

t emp. inches = inches + right . inches; temp . feet ~ feet + right , feet; temp . simplify( lj return temp ;

37 38 39

40 )

az

41 42 43

//** ••••••• ** •••••••• ** •• ** •••••••••••••••••••••

44

II Overloaded binary - operator .

//** •• * •••••••••••••••••••••••••••• **** •• ***** ••

Ri

45

i

29

30 31

More About Classes

us uf

Chapter 14

Yo

852

46

47

Feetlnches Feetlnche s : :operator - (canst Feetlnches &right)

48

{

49

Feetlnches temp;

50 51

temp . inches = inches -

52

temp . feet = fee t - right. feet;

53

temp . simplifY()i return temp;

an

ss

54 55

right.~nches;

)

Ha

The FeetInches class is designed [0 hold distances or measurements expressed in feet and inches. It consists of eight member functions: •

m

NOTE : The simplify fun ction uses the standard library function abs () to get the

uh a

o

m

• •

ad

• • • • •

A con structor: that allows the feet and inches members to be set. The default va lues for these members is zero. A setFeet function for s(O ring a value in the feet member. A setInches function for sto ring a value in the inches member. A getFeet function for returnmg the value in the feet member. A getInches function for returning the value in the inches member. A simplify function fo r normalizing the values held in feet and inches. This function adjusts any set of values where the inches member is greater than 12 or less than O. An operator + functi on that overloads the sta ndard + math operator. An operator - function that overloads the standard - math operaror.

M

abso lute value of the inches member. The abs (J function requires that cstdlib be included.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.5 Operator Overloading

853

us uf

i

The overloaded + and - operatOrs allow one Feetlnches object to be added to or subtracted from another. For example, assume the lengthl and length2 ob jects a re defined and initialized as follows! Fee t lnches lengthl{3, 5), length2{6 , 3);

length3

=

Yo

The lengthl object is holding the value 3 feet 5 inches, and the length2 object is holding the value 6 feet 3 inches. Because the + operator IS overloaded, we can add these twO objects in a statement such as: lengthl + length2;

az

This statement will add the val ues of the lengthl a nd length2 objects and store the result in the length3 object. After the statement exec utes, the length3 object will be set to 9 feet 8 inches.

Ri

The member functio n tha t overloads the + operato r appea rs in lines 33 through 41 of the Feetlnches . cpp 6le.

an

This function is ca lled anytime the + opera tOr is used with two FeeUnches objects. JUSt like the overloaded = operatOr we defined in the previous section, th is function has one parameter: a constant reference object named right. This parameter references the object on the right side of the operatOr, For example, when the followi ng statement is executed, right w ill reference tbe length2 object:

ss

length3 = lengthl + length2;

As before. it might be helpful to think of the sta tement above as the following functi on call:

= lengthl.operator+(length2);

Ha

length3

T he length2 object is being passed to the function's p.:lrameter, right. When the fu nction 6nishes, it will return a Feetlnches object to length3. Now let's see what is happenlng inside the fu nction. First, notice that a FeetInches object named temp is dc6ned locally in line 35:

ad

Feetlnches temp;

m

This object is a temporary location for holding the results of the addition. Next, line 37 adds inches to right. inches an d stores the result io temp. inches: temp. inches

=

inches + right , inches;

uh a

m

The inches varia ble is a member of lengthl, the object making the function call. It is the object on the left side of the operator. right. inches references the inches member o f length2 . The next Statement, in line 38, is very similar. It adds feet to right. feet and stOres the resu lt in temp , feet:

M

temp. feet

= feet

+ right. feet ;

At this point in the function, temp conta ins the sum of the feet and inches members of both objects in the expression. The next step is to adjust the values so they conform to a normal value expressed in feet and inches. This is accomplished in line 39 by cal1ing temp. simplify ( ): temp. simplif y{ ) i

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 854

Chapter 14

More About Classes

us uf

i

T he last step, in line 40, is to return the vallIe stored in temp: return temp ;

In the statement length) = length l + length2, the return statement in the operator funct ion causes the va lues stored In t e mp to be returned to the l ength3 objeer.

Yo

Program 14-8 demonstrates rhe overloaded operators. (This file is stored in the student source code fo lder Chapter 14\Feetlnches Version 1.) Program 14-8

II This program demonstrates the FeetInches class's overloaded II + and - operators .

3

' i nclude <iostream> I include "Feetlnches . h"

5

using names pace std;

8 9 10

11 12

13

int main () {

int feet, inches;

II To hold inpu t

/1 Create three Feetlnc hes objects . The default arguments II for the constructor will be used . Feetlnches first, second, thi r d;

14

ss

II Get a distance from the user . cout « "Enter a distance in feet and inches: "; cin » feet » inches;

Ha

15 16 17 18 19 20 21

II Store t he distance in the first object . first.setFeet(feet); first.set Inc hes( i nches);

22

ad

II ASSign first + second to third. thir d : first + second ; II Display the result . cout « "first + second = "; cout « third . getFeet() « " feet, "; cout « third . getInches ( ) « " inches . \ 0 ";

uh a

31 32 33 34 35 36 37

II Store the distance in second . second . setFeet( f eet ); second . setInches(inches ) ;

m

30

II Get another distance f r om the user . cout « "Enter anothe r distance in feet and inches : "i cin » feet » inches;

m

23 24 25 26 27 28 29

for feet and inches

an

6 7

Ri

4

az

1 2

M

38

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.5 Operaror Overloading

i

II Assign first - second to third . = first - second;

us uf

39

40

third

41 II Dis play

43

cout « cout « cout «

44 45 46

47

return 0;

48

az

Program Output with Example Input Shown in Bold Enter a distance in feet and inches: 6 S [Enter] Enter another distance in feet and inches: 310 [Enter] first + second = 10 feet, 3 i nches .

Yo

the re su lt. "first - second == "; third . getFeet () « " feet, "; t hird . getInches () « " i nches. \n " ;

42

855

Ri

fir s t - second - 2 feet , 7 inches .

Overloading the Prefix ++ Operator

++distance ;

Ha

ss

an

Unary operators, such as ++ and --, are overloa ded in a fashion sim ilar to the way binary operators are implememed. Because unary operators only affect the object making the operator function ca ll , however, there is no need for a parameter. For example, ler's say you wish to have a prefix incremem operator for the Feetl nches cl ass. Assume the Feetl nches object distance is set to the values 7 feet and 5 inches. A ++ operator function could be designed to increment the object's inches member. The followi ng statemem would cause distance ro have the value 7 feet 6 inches:

T he following function overloads the prefix

++

operator to work in this fas hion:

Feetlnches Feetlnches :: operator++() (

m

)

ad

++ i nches ; simplify() ; r eturn "this;

m

Th is function first increments the object's inches member. T he simplify () funcrion is called and then the derefercnced t his pointer is returned. This allows the operator to perform properly in statementS like this: distance2

~

++distancel;

uh a

Remember, the statement above is equivalent to

M

distance 2 = d is tancel . operator++();

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 14

More About Classes

i

856

us uf

Overloading the Postfix ++ Operator

Overloading tne postfix ++ operator is only slightly different rhan overloading the prefix version. Here is the function fhar overloads the postfix operator with the Feetlnches

class:

Yo

Feetlnches Feetlnches::operator++(int) Feetlnches temp(feet, inches);

inches++i simplify ( ) ; return tempi }

= distance1 ++i

ss

distance2

an

Ri

az

The first difference you will notice is the use of a dummy parameter. The word int in the function 's parentheses establishes a nameless integer parameter. When C++ sees this parameter in an operator function, it knows the function is designed to be used in pOSt fix mode. The second difference is the use of a temporary local variable, the temp object. temp is initi alized witb the feet and inches va lues of the object making the function call. temp, therefo re , is a copy of the objec t being incremented , bur before the increment takes pla ce. After inches is incremented and the simplify function is ca lled, the COll tentS of temp is returned. This causes the postfix operata!路 to behave correctly in a sratement like this:

Ha

You will find a version of the Feetlnches class with the (>verloaded prefix and postfix ++ operarors srored in the Student Source Code Folder Chapter 14 \Feetlnches Version 2. In rhat folder yOlI will also find Program 14-9, which demonstrates these overloaded operatoc$. Program 14-9

1 II This program demonstrates the Feetlnches class's overloaded 2 II prefix and postfix ++ operators. linclude <iostream> 'include "Feetlnches . h" using namespace std;

ad

3 4 5 7

int main()

8

{

10

int count;

II Loop counter

m

9

m

6

12

II Define a Feetlnches object with the default II value of 0 feet, 0 inches .

13

Feetlnches first;

uh a

11

14 15

16

II Define a Feetlnches object with 1 foot 5 inches. Feetlnches second(l, 5);

M

17

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 8 57

25 26 27 28

II Us e t he po stfix ++ o p e ra tor. c ou t « "\n D emo n s t~ a t i ng p os t fix ++ o p erator . \n" ; f o r (co u nt = 0 ; coun t < 12 ; c oun t++ )

32

{

36 37 38

3' 40

= s eco n d++; « « « «

"f i r st : " « f irs t. get Fee t () « " f eet , "i fi rst. g e t lnche s() « " inche s . "j " sec o nd: " « s ec o nd . g e t Fe e t () « fee t , " i second.get l n c h es() « " inches . \ n";

Ri

firs t cout cout cout c ou t

33 3' 35

az

30 31

)

an

29

.

us uf

2.

I I Use t he p r e fi x ++ ope r a tor. cout « "Demo nstrat ing pre f i x ++ o p erator . \ n"; fo~ (cou nt = 0 : cou nt < 12; coun t ++ ) ( f irst = ++SeCOndi c out « "f irs t : " « first. get Fe et ( ) « " feet, " ., cou t « f irst. g e tlnc hes { ) « " inc hes . " , feet, " ., cout « "sec ond : " « se c o nd . g etFee t ( ) « cout « second . g e t l nc hes( ) « " i nches. \n " i )

Yo

18 19 20 21 22 23

i

14.5 Operator Overloading

re tu rn 0;

41

Ha

ad

postfix: ++ o perator . 5 inches . second: 2 feet 6 inches . 6 inches . second : 2 feet 7 inches . 7 inches . second: 2 feet 8 inches . 8 inches . second: 2 feet 9 inches. 9 inches . second: 2 feet 10 inches . 10 inches . second: 2 feet 11 inches . 11 i nches . second: 3 feet 0 inches. 0 inches . second: 3 feet 1 inches. 1 i nches. second: 3 feet 2 inches. 2 inches _ seco nd: 3 feet 3 i nches . 3 inches. second : 3 feet inches. inches . second: 3 feet 5 inches .

M

uh a

m

Demonstrating first: 2 feet first : 2 feet first : 2 feet first : 2 feet first : 2 feet f irst : 2 feet first : 2 fee t first: 3 feet first: 3 feet first: 3 feet first : 3 feet first: 3 feet

prefix ++ operator. 6 inches. second : 1 feet 6 inches . 7 inches. second : 1 feet 7 inches . 8 inches. second: 1 feet 8 inches . inches. second : 1 feet 9 inches . 10 inches. seco nd : 1 feet 10 inches . 11 i nches. second : 1 feet 11 inches . 0 inches. s econd: 2 feet 0 inches . 1 inches. second : 2 feet 1 inches . 2 inches . second : 2 feet 2 inches . 3 inches. second : 2 feet 3 inches . inches . second : 2 feet inches . 5 inches . second : 2 feet 5 inches .

m

Demonstrating first: 1 feet first : 1 feet first: 1 feet first: 1 feet first: 1 feet first: 1 feet firs t : 2 feet first : 2 feet first : 2 feet first : 2 feet first : 2 feet first : 2 feet

ss

Program Output

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Checkpoint 14. 14 14.15

us uf

~

More About Classes

i

Chapter 14

858

Assume there is a class named Pet. Write the prototype for a member function of Pet that overloads the =operaror. Assume that dog and cat are instances of the Pet class, which has overloaded the

=operator. Rewrite the following statement so it appea rs in funct ion call notation

Yo

instead of operator notation: dog "" ca t ;

=operaror return ing void?

What is the disadvantage of an overloaded

14. 17

Describe t he purpose of the th i s pointer.

14.18

The this po imer is automatically passed to what type of funct ions?

14.19

Assume there is a class named Animal that overloads the =and + operators. In the following sta tement, assume cat, tiger, and wildcat arc all instances of the

az

14.16

Animal class:

Ri

wildcat = cat + tiger; Of the three objects, wildcat, cat, or tiger, which is calling the operator+ func t ion? W hich object is passed as a n argument into the function? W hat does the use of a dummy parameter in a unary operator function indicate w the compiler?

an

14.20

ss

Overloading Relational Operators In add ition to the ass ignment and math operators, relationa l operators may be over-

Ha

loaded. T his capability allows classes to be compared in statements that use rela tional expressions such as: i f (distancel < distanCe2) {

ad

... code ...

Overloaded relational operators are implemented like other binary operators. The only

m

d ifference is that a rel at io nal operator func tion should always return a true or false val ue. The Feetlnches class in the Student Source Code Fo lder Chapter 14 \ FeetInches Version 3 contains functions to ove rload the >, <, and == reiarionai operators. Here is the functio n for overloading the> operator:

m

bool Feetlnches: : operator > (const Feetlnches &right) {

M

uh a

bool status ;

if (feet> right . feet) status'" true;

else if (feet == r ight .feet && inches status true ; else status -= false ;

~

right. inches)

r e turn status; }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 859

14.5 Operator Overloading

H ere is the code tha t overloads the < operator: bool Feetlnches: : operator < (canst Feetlnches &r i ght) {

Yo

bool status ;

us uf

i

As you can see, the funct ion compares the feet member (and if necessary, the i nches member) with that of the parameter. If the call ing object contains a value greater than that of the parameter, true is returned. Otherwise, false is returned.

az

i f (feet < right .feet) status - true ; else if (feet == right . feet && inches < right . inches) status = true; else status false;

Ri

return status; )

H ere is the code that overloads the -- operator: {

bool status;

==

(canst Feetlnches &right)

an

bool Feetlnches::operator

right . inches)

Ha

ss

if (feet == right. f eet && inches status - true; else status fa l s~ ; return status ; }

Program 14-10

II This program demonstrates the Feetlnches class·s overloaded

m

II relational operators. 'include <iostream> 'incl ude "Feetlnches . h" using names pace std;

6

i nt main() {

uh a

7 8

9

also stored III the

m

1 2 3 4 5

IS

ad

Program 14-10 demonstrates these overloaded operators. (This fi le Student Source Code Folder Chapter 14\Feetlnches Version 3.)

int feet, i nches;

II To hold input for fe et and inches

10

11

II Create two Feetlnches ob jects . The default arguments

12

for the con~tructor will be used . Feetlnches first, second;

M

13

II

14 15 16 17

II Get a distance from the user . cout « "Enter a distance i n feet and inches : "; cin » feet » inches;

18

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 860

Chapter 14

More About Classes

19

II Store the distance i n first.

20

first.setFeet(feet); first.setlnches(inches);

21

"

25

Yo

/1 Get anot her distance . cout « "Enter another distance in feet and inc hes : " ; c in » fee t » inches ;

23 24 26

II Store the distance in second. second.setFeet( f eet) ; second.s etlnches(inches) ;

27

28 29

us uf

i

(continued)

1/ Compare t he two obj ec ts . : = second) cout « "first is equal to second . \n" ; if (first> second) cout « " first is greater than second.\n"; i f (fi rs t < second)

31 33

34 35 36 37 38 39

"first i s less than second . \n" ;

return 0;

an

40

cout«

Ri

if (firs t

32

az

30

}

Program Output with Example Input Shown In Bold

Ha

first is greater than second.

ss

Enter a distance in feet and inches: 6 5 (Enter] Enter another distance in feet and inches: 3 10 [Enter]

Program Output with Different Example Input Shown In Bold

Enter a distance in feet and inches : S S [Enter] Enter another distance in feet and inches: 5 5 [Enter] first is equal to second .

ad

Program Output with Different Example Input Shown In Bold Enter a distance in feet and inches: ) 4 [Enter] Enter another distance in feet and inches : 3 7 [Enter]

m

first is less than second.

and» Operators

m

Overloading the«

M

uh a

Overloading the math and relational operators gives you the ability ro write those types of exp ressions with class objects just as naturally as with integers, floats, and other built-i n data types. 1£ an object's primary data members are priva te, however, you still have to make expl icit member fu nct ion calls to send their values to couto For example, assume distance is a Feetlnches object. The following statements display Its internal values: cout « cout «

distance . get Feet () « .. fee t, "; distance. get Inches () « "inches";

[t is also necessary to explicitly call member functions to set a FeetInches object's da ta. For instance, the following statements set the distance object to useNpecined va lues:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 861

14.5 Operator Overloading

us uf

i

cout « "Ente r a value in feet : " ; cin » f; distance . setFeet(f l i cout « "Enter a value in inches : "i cin » ii distance . setInches(ili

cout «

Yo

By overloading the stream insertion operaror (<<), yo u could send the distance object to cout, as shown in the following code, and have the screen output automatically formatted in the correct way. distance ;

cin »

az

Likewise. by overloadi ng the stream extraction operator (»), the distance object could take values directly from cin, as shown here. distance;

ostream &operator «

ss

an

Ri

Overloading these operarors is done in a slightl y different way, however, than overloading other operators. These operators are actually parr of the ostream and istream classes defined in the C++ runtime li brary. (T he cout and dn objects are insta nces of ostream and istream.) You must write operaror funct ions to overload the ostream version of« and the istream version of », so they work directly with a class such as FeetInches. T he FeetInches class 1O the Student Source Code Folder Chapter 14\Feetlnches version 4 contain s fUllctions to overload the « and » oper.ators. H e re is the function that overloads the « operator: (ostream &strm , canst Feet l nches &objl " feet, " «

Ha

strm « obj . feet « return strm; )

obj.inches «

" inches";

m

ad

Notice the function has two parameters: a n ostream refe rence object and a const Feetlnches reference ob ject. The ostream parameter will be a reference to the actual ostream object on rhe left side of rhe « operator. The second parameter is a refere nce to a Feet Inches objecr. This parameter will reference the object 011 the right side of the <] operator. This funcrio n rells C++ how to handle any expressio n that has the following form: ost r eamObject «

FeetInchesObject

m

So, when C++ encounters rhe following S£a temem, it will call the overloa ded operator« function:

uh a

cout «

distance;

M

Notice tha t the function's return type is ostream &. T his means that the function ret urns a reference to an ostream object. When rhe return strm; statement executes, it doesn't return a cop y of strm, bu t a reference to it. This allows you to chai n togethe,' severa l expressions using rhe overloaded « opera we, such as: eout «

distancel

«

"

" «

distance2

«

endl;

Here is the function that overloads the stream ext raction operator Feet l nches class:

[Q

work with the

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 14 More About Classes

(istream &strm, Feetlnches &obj)

{

II Prompt the user for th e feet. cout « strm »

i

istream &operator »

us uf

862

"Feet: "; obj .f eet;

Yo

/1 Prompt the user for the inches. cout « " Inches : "; strm » obj.inches: /1 Normalize the values. obj.s i mpl ify();

az

return strm; }

istreamObject »

FeetInchesObject

Once again, the function returns a reference

Ri

T he same principles hold [me for this operator. It tells C++ how to handle any expression in the fo llowing form:

to

an istream object so several of these

an

expressions may be chamed together.

You have probably realized char neither of these functions is quite ready to work, though. Both functions anempt to directly access the Feetlnches object's private members. Because

Ha

ss

the functions aren't themselves members of the Feetlnches class, they don't have this type of access. The next step is to make the operator functions frie nds of FeetInches. This is shown in the following listing of the FeetInches class declaration. (This file is srored in the Student Source Code Folder Chapter 14 \Peetlnches Versio n 4. )

ad

NOTE: Some compilers require you to prolOtype the» and« operator functions outside the class. For th is reason, we have added rhe following sratements to the FeetInches . h class specification file.

II Forward Declaration

class FeetI nches;

m

m

II Function Prototypes for Overloaded Stream Operators ostream &operator « (ostream &, canst Feetlnches &); istream &operator » (istream &, FeetInches &); Contents of Feetln c he s. h (Version 4)

uh a

1 2

j ifndef FEET INCHE S H jdefine FEET INCHES H

3

4 5

'include <iostream> using namespace std;

M

6

7 8

c la ss Feetlnchesi

II Forward Declaration

9 II Function Prototypes for Overloaded Stream Operators 10 11

ostream &operator « istream &operator »

(ostream &, const Feetlnches &); (istream &, Feetlnches &);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.5 Operator Overloading

/1 The Feetlnches class holds distances or measurements

14

II expressed in feet and inches.

15 class Feetlnches {

18

private: iot feet ; /1 To hold iot inches; /1 To hold void simplify(); // Defined public : 1/ Constructor Feet lnches(int f = 0, int i { feet = f; inches - i; simplify{) ;

19 20

21

22 23 24 25 26 27

a number of feet a number of inches in Feetlnches.cpp

Yo

17

: 0)

az

16

29

II Mutator functions void setFeet(int f) { feet = f; }

31

32 void setlnches(int i) { inches m i; simplify(); }

37

II Accessor functions int getFeet() const { return feet; }

ss

an

33 34 35 36 38

39

Ha

40 41

int getlnches() const { return inches; )

42 43

// Overloaded operator functions Feetlnches operator + (canst Feetlnches '); /1 Overloaded + Feetlnches operator - (canst Feetlnches ')i /1 Overloaded Feetlnches operator ++ (); /1 Prefi x ++ Feetlnches operator ++ (int); II Postfix ++ baol operator> (canst Feet lnches &); /1 Overloaded> bool operator < (const FeetInches &); /1 Overloaded < bool operator == (canst Feetlnches '); /1 Overloaded ==

44 45

48 49

m

50

ad

46 47

Ri

28 30

us uf

i

n 13

S63

m

51 52 53 54 55

II Friends friend ostream &operator « friend istream &operator »

};

58

lendif

uh a

56 57

(ostream &, canst Feetlnches &); (istream &, Feetlnches &):

Lines 54 and 55 in the class declaration tell C++ to make the overloaded« and » opera-

M

tor functions friends of the Feetlnches class: friend ostream &operator«(ostream &, const Feetlnches &); friend istream &operator»(istream &, Feetlnches &);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 864

Chapter 14

More About Classes

us uf

i

These statements give the operator functions direer access to the FeetInches class's private members. Program 14-11 demonstrates how the overloaded operators work. (This file IS also stored in the Student Source Code Folder Chapter 14\Feetlnches Version 4.)

1 2 3 4

1/ This program demonstrates the « and » operators, /1 overloaded to work with the Feetlnches class . #include <iostream> 'include "Feetlnches.h"

5 6

using namespace std;

7 8

iot main()

az

{

Feetlnches first, second;

11

II Get a distance for the first object. cout « "Enter a distance in feet and inches . \n"; ein » first:

15 16

1/ Get a distance for the second object.

an

cout « "Enter another distance in feet and inches. \n"; cin » second;

17 18

II Display the values in the objects . cout « "The values you entered are : \n"j cout « first « " and " « second « endl; return OJ

ss

19 20 }

Ha

21 22 23

II Define two objects.

Ri

9 10 12 13 14

Yo

Program 14- 11

Program Output with Example Input Shown In Bold Enter a distance in feet and inches . Feet : 6 [Enter]

m

ad

Inches: 5 [Enter] Enter another dista nce in feet and inches . Feet: 3 [Enter] Inches: 10 [Enter] The values you entered are ~ 6 feet , 5 inches and 3 feet, 10 inches

m

Overloading the [] Operator

uh a

In addition to the traditional operators, C++ allows you to change the way the [) symbols work. This gives you the ability to write classes that have array-like behaviors . For example. the string class overloads the [1 operator so you can access the individual characters stored in string class objects. Assume the fo llowing definition. exists in a program:

,

M

string name"" "william'"

.

The first character in the string, ' W,' is stored at name [ 0], so the following statement will

display W on the sc reen. cout «

name[O];

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 865

i

14.5 Operator Overloading

Contents of IntArra y. h 1/ Specification file for the IntArray class 'ifndef INTARRAY H 'define INTARRAY H

5

class IntArray

(

7

private : lnt *aptr; int arraySize; void subscriptError() ; public : IntArray(int); IntArray(const IntArray &): - IntArray ( ) :

12 13 14 15 16 17 18 19 20

21

II Constructor II Copy constructor II Destructor

iot size() const { return arraySize; }

II Returns the array size

int &operator[)(const int &);

II Overloaded [] operator

an

II

1/ Pointer to the array II Holds the array size II Handles invalid subscripts

}i

Jendi£

ss

8 9 10

az

6

Ri

Yo

1 2 3

us uf

You can use the overloaded [ J operaror to create an array class, like the foHowing one. The class behaves like a regular array, but performs the bounds-checking that C++ lacks.

// Implementation file for the IntArray class 'include <iostream> linclude <cstdlib> II For the exit function ilinclude "IntArray.h" using names pace stdi

ad

1 2 3 4 5

Ha

Contents of IntArray. c pp

6

7 8

m

9

11**************************************************** *** /1 constructor for IntArray class. Sets the size of the * II array and allocates memory for it. •

11

IntArray::lntArray{int 5)

13

{

m

12

uh a

14 15 16 17

18

arraySize = Si aptr = new int [sJ; for (int count = 0: count < arraySizei count++) *(aptr + count) = 0;

)

"

M

20 21

22 23

Copy Constructor for IntArray class. • 11********"*'******·**********'·*******'***********+* ++

II

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

2.

IntArray :: lntArray(Const IntArray &obj) {

arraySize ~ obj . arraySize; aptr = new int [arraySizeJi

27 28

31 32 33

34 35 36 37

38 39

for(int count = 0; count < arraySizej count++) *(aptr + count) = *(obj . apt r + count); }

Yo

29 30

11··----_·_*·_--*--------*------------------------_··**• II Destructor for IntArray c l ass. 11---------_···_------_·_·_---------------------**---- ** IntArray::-IntArray() { if (arraysize > 0)

delete [ ) aptri

43

44 45

Ri

40 41 42

//*********** ** ********** ****** ******** ****** ********** *** ***

1/ 5ubscriptError function . Displays an error message and * II terminates the program when a subscript is out of range. * 1/****** ******** ·************** **** ** * ********** * ** *** *** ****

an

46

47

void IntArray: : subscriptErrOr()

48

{

cout« "ERROR: Subscript out of range.\n"; exit(O);

ss

49 50 51

S5

56

57 58

11*************************.·***.**.*··*·**********·** *** II Overloaded (J operator. The argument is a subscript . • II This function returns a reference to the element • II in the array indexed by the subscript. • 11························· ··· ··*·········*··*······*· *. *

ad

54

Ha

52 5]

i

24 25

More About Classes

us uf

Chapter'4

az

866

59

int &IntArray::operator[](const int &sub)

60

{

i f (sub < 0 II sub >; arraySize) subscriptError(); return aptr[subJ ;

m

61 62 63 64

)

m

Before foc using on rhc overloaded operaror, let's look at the consrructors and the destructor. The code for the first constructor in lines 12 through 18 of the IntArray . cpp file follows:

uh a

IntArray: :IntArray(int s)

M

{

arraySize '" s; aptr '" new int [5] ; for (int count'" 0 ; count < arraySize; count++) *(aptr + count) '" 0;

When an instance of the class is defined, the number of elements the array is to have is passed into the constructor's parameter, 8, Th is value is cop ied to the ar r aySize member,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH , 4.5 Operator Overloading

867

ÂŁor (int count = 0; count < * (aptr + count) = 0;

arraySi~e;

us uf

i

and then used to dynamically allocate enough memory for the array. The construcror's Gna! step is to store zeros in an of the array's elements: count++)

Yo

The class also has a copy constructor in lines 24 through 30, which is used when a class object is initialized with another object's data: IntArray :: lntArray(const IntArray &obj) {

az

arraySize = obj.arraySize; aptr = new int [arraySizel; for(int count - 0; count < arraySize; count++) *(aptr + count) = *(obj.aptr + count);

}

Ri

A reference to the initializing object is passed into the parameter obj. Once the memory is successfully allocated for the array, the construc(Q( copies all the values in obj's array into the calling object's array.

{

if (arraySize > 0) delete [I aptri

Ha

}

ss

IntArray::-IntArray()

an

The destruc(Qr, in lines 36 through 40, simply frees the memory allocated by the class's cons[Cuctors. First, however, it checks the value in arraySize to be sure the array has at least one element:

The ( J operator is overloaded similarly to other operators. The definition of the operator! I function appears in lines 59 through 64: int &IntArray: :operatorl](const int &sub) {

ad

if (sub < 0 II sub >= arraySize) subscriptErrOr(): return aptr(sub]i )

m

m

The operator [ 1 funct ion can have on ly a single parameter. The one shown uses a constant reference to an integer. This parameter holds the value placed inside the brackets in an exp ress ion. For example, if table is an IntArray object, the number 12 wi ll be passed into the sub parameter in the following statement:

uh a

cout ÂŤ

table[l2];

Inside the function, the value in the sub parameter is tested by the following i f statement:

M

if

(sub < 0 I I sub >= arraySize) subscriptError();

This statement determines whether sub is within the range of the array's subscripts. If sub is less than 0 or greater than or equal to arraySize, it's not a valid subscript, so the subscriptError function is called. If sub is within range, the function uses it as an offset into the array, and returns a reference ro the value stored at that location.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 868

Chapter 1 4

More About Classes

us uf

i

One criticall y important aspect of the function above is its return type. It's crucial that the function return noc simply an integer, bur a reference co an integer. The rca son for this is that expressions such as the following must be possible: tabl e[5] ': 27;

Yo

Remember, the built-in '"'- operator requires the object on its left CO be an lvalue. An lvalue must represent a modifiable memory location, such as a variable. The integer return va lue of a function is not an lvalue. If the operator[ J funct ion merely returns an integer, it cannot be used to create expressions placed on the left side of an assignment operator.

A reference to an integer, however, is an Ivaluc. If the operator [ 1 function returns a reference, it can be used ro create expressions like [he following:

az

table!7] : 52;

Ri

In this sta tement, the operator[ 1 fu nction is called with 7 passed as its argument. Assuming 7 is within range, the function returns a reference to the integer stored at (aptr + 7). Tn essence, the statement above is equivalent [0: *(aptr + 7) : 52 ;

an

Because the operator[ J function returns actual integers stored in the array, it is not necessary for math or relational opera tors ro be overl oaded . Even the stream operarors « and» will work just as they are with the I ntArray class.

ss

Program 14-12 demonstrates how the class works. Program 14-12

4 5 6 7 8

This program demonstrates an overloaded il operator . 'include <iastream~ hnclude "IntArray . h" using names pace std ;

int main()

ad

2 3

Ha

1 II

{

canst int SIZE

9

10 elements .

IntArray table(SIZE);

II Store values in the array . for (int x = 0; x < SIZE; x+ +) table[x ] - (x * 2Ji

uh a

13 14 15 16 17 18 19 20

II Define an IntArray with

m

12

Array size

m

10 11

= 10 ; II

M

21 22

23

24

II Display the values in the array . for (int x = 0; x < SIZE; x++) cout « table[xJ « " "; cout « endl; II Use the standard + operator on array elements . for (int x = 0; x < SIZE ; x++) tablelx] = table(xl + 5;

25

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 869

28 29 30 31

// Use the standard ++ operator on array elements. for (int x = 0: x < SIZE: x++) table\xj++:

32 33 34

II Display the values in the array. for (i nt x : 0; X < SIZE; x++) cout « table[x) « " ": cout « endl;

37 JB J9

az

35 36

return 0;

40 )

Ri

41

Program Output

o

us uf

// Display the values in the array . for lint x = 0 : x < SIZE; x++) cout « table[x) « " "; cout « endl:

27

Yo

26

i

14.5 Operator Overloading

2 4 6 8 10 12 1 4 16 18

an

5 7 9 11 13 15 17 19 21 23 6 8 10 12 14 16 18 20 22 24

Program 14-13 demonstrates the IntArray class's bounds-checking capability.

II This program demonstrates the IntArray class's bounds-checking ability .

2 'include <iostream> 3 'include "IntArray.h" 4 using namespace std : 5

6 int main() 7 {

const i nt SIZE

= 10;

// Array size

ad

8 9 10 11

Ha

1

ss

Program 14- 13

II Define an IntArray with 10 elements . IntArray table(SIZE) :

m

12 13

1/ Store values in the array. for (int x = 0; x < SIZE : x++) table(x] = x ;

m

14 15 16

II Display the values in the array . for (int x = 0; x < SIZE; x++) cout:. « table[xj « " ", cout « endl;

17

uh a

18

19

20

21 22

1/ Attempt to use an invalid subscript . cout « "Now attempting to use an invalid subscript . \n"; table[SIZE + 1) = 0: return 0;

2]

M

24 25 26

}

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 870

Program 14·13

i

Chapter 14 More About Classes

us uf

(continued)

~

Yo

Program Output 01234 567 8 9 Now attempting to use an invalid subscript. ERROR : Subscript ou t of range .

Checkpoint 14.21

Descr ibe the values that should be returned from funer ions that overload relational operators.

What is [he advamage of overloading the« and »operators?

14.23

What type of object should an overloaded «operator function return?

14.24

What type of object should an overloaded» operator function reru m ? If an overloaded « or »operator accesses a private member of a class, what

az

14.22

Ri

14 .25

must be done in that class's declaration?

Assume the class NUrnList has overloaded the ( J operator. In the expression below,listl is an insta nce of the NumList class;

14.26

an

listl\25l

ss

Rewrite the expression above to exp licitly call {he funct ion that overloads the [1 opera tor.

Ha

Object Conversion

ad

CONCEPT: Specia l operator fu nctions may be written to convert a class obj ect to any other type.

m

As you've already seen, operator functions allow classes to work mo re like built-in data types . Another capability that operator functions can give classes is au tomatic type conve rsIOn.

m

Data type conversion happens "behind the scenes" with the built-in data types. For instance, suppose a program uses the following var iables: int ii

uh a

double d;

The statement below automatically converts the value in i to a floating-point number and Stores it in d:

M

d '" i;

Likewise, the following statement converts the value in d to an integer (truncating (he fractional part) and stores it in i: i

- d;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 871

i

14.6 Obiect Conversion

us uf

The same functionality can also be given to class objects. For example, assuming distance is a FeetInches object and d is a double, the following Statement would conveniently convert distance's value into a floating-point number and StOre it in d, if Feetlnches is properly written : d '" distance ;

Yo

To be able to use a statement such as this, an operator function must be written to perfo rm the conversion. The Student Source Code f older Chapter 14 \Feet l nches Version 5 contains a version of the Feetlnches class with such an operator function. H ere is the code for the operator function that converts a Feetl nches o bject to a double: Feetlnches :: operator double( ) =

feet,

temp += (inches I 12 . 0) ; return tempi )

Ri

double temp

az

{

an

T his function contains an algorithm that wil l calculate the decimal equivalent of a feet and inches measurement. For example, the value 4 feet 6 inches will be converted to 4.5. This value is stored in the local variable temp. The temp variable is then returned .

Ha

ss

NOTE: No return type is specified in the function header. Beca use the fu nction is a Feetlnches-to- double conversion function, it Will always return a double. Also, because the function takes no arguments, there are no parameters.

The revised Feetlnches class nlso has an operator function tha t converts a Feetlnc hes object to an into T he function, shown he re, simply returns the feet member, thus truncating the inches value: Feetlnches :: operator int()

ad

{

return feet;

m

Program 14-14 demonstrates both of these conversion functions. (This file is also stored in the Scudenr Source Code Folder Chapter 14 \FeetInches version 5.)

2

II This prog r am demonstrates the the Feetlnches class's II conversion functions .

3 4 5

'inc l ude <i08tream> 'include "Feetlnches . h" using names pace stdj

uh a

1

m

Program 14-14

6

int main()

8

{

M

7

9

10

double d; int i;

II To hold double input I I To hold int input

11

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 14-14

i

More About Classes

12 13

II Define a Feet l nches object . Fe et l nches distance ;

15

II Get a distance f r om the use r. cout « "Enter a d ista nce i n f eet a nd i nches : \0" ; cin » d i stance:

I.

I. 17 18 19 20 21 22 23 24 25 2. 27 28

II Convert the distance object to a dou b le. II Convert the d i st a nce object to an into i = distance;

Ri

II Display the values . cout « "The value " « distance; cout « " is equivale nt to " « d « " feet\n" ; cout « "or" « i « .. f eet, rounded down. \ 0 " ; retur n 0;

29

30

az

d = distance;

us uf

(continued)

Yo

Chapter 14

872

)

an

Program Output with Example Input Shown In Bold

~

Ha

ss

Enter a distance i n feet and inches: Fee t : 8 [Enter] I nc hes: 6 [Enter] The value 8 f eet , 6 inche s i s equiva lent to 8.5 fe e t o r 8 fee t , r ound e d down.

See the Case Study on Creating a String Class on the Student CD.

~ Checkpoint

When overloading a binary operator such as + or -, what object is passed into the operator function's parameter?

14.28

Explain why overloaded prefix and postfix ++ and -- operator functions should retu rn a value. How does C++ tel l the difference between an overloaded prefix and postfix ++ or -- opera tor function?

m

ad

14.27

14.29

Write member fu nctions of the FeetI nches class that overload the prefi x and postfix -- ope rators. Demonstrate the functions in a simple program similar to Program 14·14.

uh a

m

14.30

Aggregation

M

CONCEPT: Aggregation occurs when a class contains an instance of another class. In rea l tife, objects are frequently ma de of other objects. A house, for example, is made of door objects, window objects, wall objects, and m uch more. It is the combi na rion of all t hese objects [hat makes a house object.

Class Aggregation

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 873

i

14.7 Aggregation

T he course name The instrucror's last name, first name, and office number T he textbook's title, author, and publisher

Yo

• • •

us uf

When designing software, it sometimes makes sense to create an object from other objects. For example, suppose you need an object to represent a course that you are taking in college. You decide ro create a Course class, which will hold the following informa6on:

az

In addi tion to the course name, the class will hold items related ro the instrucror and the textbook. You could put attributes for each of these items in the Course class. However, a good design principle is to sepa rate related items into their own classes. In this example, an Instructor class could be created to hold the instructor-related data and a TextBook class could be created to hold the textbook-related data . Instances of these classes could then be used as attributes in the Course class .

Ri

Let's take a closer look at how this might be done. To keep things simple, the I nstructor class wi ll have on ly the following functions: A default conStructOr that assigns empty strings to the instructor's last name, fi rst name, and office number. A constructor that accepts arguments for the instrucror's last name, first name, and office number A set function tha t can be used to set all of the class's attributes A print function that displays rhe object's attribute values

an

ss

• •

The code for the Instructor class is shown here:

3 4 5

'if ndef INSTRUCTOR 'de f ine INSTRUCTOR 'include <iostream> 'include <cstring> using namespace std;

ad

1

2

Ha

Contents of Instructor. h

6

7

II Constants for array sizes const int NAME_SIZE = 51; const int OFFICE NUM SIZE ~ 21;

m

8 9

10

II Instructor class class I nstructor

14 15 16

private : char lastName[NAME_SIZE} ; char firstName(NAME_SIZE];

17

char officeNUmber[OFFICE_NUM_SIZEj ; II Office number public: /1 The default constructor stores empty strings II in the char arrays. Inatructor ( ) { set{"'·, ""f .'.') ; )

uh a

m

11 12 13

M

18

19 20 21

22 23 24

25

{ II Last name II First name

II Constructor Instructor(char *lname, char *fname, char *office)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

More About Classes

{ set(lname, fname, office); }

26 27

II set function void set(const char *lname, const char *fname, const char *office) ( strncpy (!astName, Iname, NAME_S I ZE); lastName(NAME_SIZE - 1) = '\O'i

28 29

30 31 32

Yo

33

34 35

str ncpy(firstName, fname, NAME_S I ZE) ; firstNameiNAME_SIZE - 1] = '\0' ;

36 37 38 39 40

II print function

41

void print() const

strncpy{officeNumber, office, OFFICE_NUM_SIZE); officeNumberIOFFICE_ NUM_SIZE - I) '\0'; }

44

·, Last name : " « lastName « endl ; "First name : " « firstName « endl; "Office number: " « officeNumber « endl ; }

cout« cout « cout «

Ri

{

43

az

=

42

45 46

us uf

Chapter 14

874

}; 'endif

an

The code for the TextBook class is shown next. As before, we want to keep {he class simple. The only functions it has are a default constructor, a constructor that accepts argu-

ss

ments, a set function, and a print funct ion.

Contents of TextBoo k . h

5 6 7

a

II Constant for array sizes canst int PUB SIZE = 51 ; II TextBook class class TextBook

m

9 10

Ha

3 4

lifndef TEXTBOOK 'define TEXTBOOK 'include <iostrearn> 'include <cstring> using namespace std ;

ad

1 2

11

(

13

priva te : char title(PUB_SIZEJ i II Book title char aut hor(PUB_ SIZEj; I I Author name char publisher(PUB_SIZE]i II Publisher name public : II The defaul t constructor stores empty strings II in the char arrays . TextBook() ( set("H , "", ""J; )

m

12 14

15 16

uh a

17

IB

19

20

M

21 22

23 24 25

1/ Constructor TextBook(char *textTitle, char *auth, char ·pub) { set(te xtTitle , auth , pub); }

26

27

II set function

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 875

30 31 32 33 34

us uf

void set(const char *textTitle, const char *auth, const char *pub) { strncpy(title, textTitle , PUB_SIZE); titlelNAME_SIZE - 11 : '\0';

28 29

strncpyjauthor , auth, PUB_SIZE); author ( NAME_SIZE - 1) = '\0';

Yo

35

i

14.7 Aggregation

strncpy(publishe r , pub, pue SIZE) ; publisher[OFFICE_NUM_SIZE - IJ = '\0 ' ; }

36 37 38

41

42 43 44

};

4S

8endif

az

II print function void print() canst { cout« "Title : " « title « endl ; cout « "Author : " « author « endl; cout « "Publis her : " « publisher « endl; }

Ri

39 40

ss

an

The Course class is shown neXL Notice thac the Course class has an Instructor object a nd a TextBook object as membe r variables. T hose objects are used as attributes of the Course object. Making an insrance of one class an attribute of another class is called object aggregation. The word aggregate means "a whole that is made of consti tuent parts." rn t his example, the Course class is an aggregate class because an instance of it is made of constituent objects.

Ha

When a n instance of one class is a member of another class. it is said that there is a "has a" relationship between the classes. For example, the relationships that exist among the Course, Instructor, and TextBook classes can be described as follows: The course has an insrrucror. The course has a textbook.

• •

ad

The "has a" relationship is sometimes called a whole-part relationship because one object is part of a greater whole.

m

Contents of Course. h 1

2

m

3

4

uh a

5 6

7

8 9 10

'ifndef COURSE 'define COURSE 8include <iostream> iinclude <cstring> 8i nclude "Instructor . h" linclude "TextBook.h" using names pace std i

II Constant for course namg const int COURSE SIZE = 51;

M

11

12 13 14 15 16

17

class Course private : char courSeName{COURSE_SIZE1; Instructor instructor; TextBook textbook ;

II Course name II Instructor II Textbook

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

18

More About Classes

public :

us uf

Chapter 14

19

II constructor

20 21

Course(const char *cQurse, canst char *instrLastName, canst char *instrFirstName, const char *instrOffice, canst char *textTitle, canst char *author, canst char ·publisher) ( 1/ Assign the course name .

22 23

2.

strncpy(courseName, course, COURSE_SIZE);

courseName[COURSE_SIZE - 1]

~

'\0' :

II Assign the instructor .

28

Yo

25

26 27

31

II Assign the textbook. textbook.set(textTitle, author, publisher); }

32 33

II print function void print() canst ( cout« "Course name: " «

36

cout «

37 38

cQurseName «

endl «

"Instructor Information:\n";

<l

an

instructor.print(); cout « "\nTextbook Information:\n"; textbook . print(); cout « endl ; }

39 40

42 43

Ri

34 35

az

2' 30

instructor.set(instrLastName, instrFirstName, instrOffice);

}; lendif

ss

876

Ha

Program 14-15 demonstrates the Course class. Program 14- 1 5

6 7 8 9 10

int main() ( II Create a Course object . Course myCourSe("Intro to Computer Science", II Course name "Kramer", "Shawn", "RH3010" II Instructor info "Starting Out with C++", "Gaddis", II Textbook title and author "Addison-wesley"); II Textbook publisher

ad

3 4 5

II This program demonstrates the Course class. 'include ·'Course.h"

m

1 2

m

11

I

II Display the course info. myCourse.print(); return 0;

12

13

uh a

14 15

)

Program Output Course name: Intro to Computer Science

M

Instructor Information: Last name: Kramer First name: Shawn Office number: RH3010

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

endl;


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

8 77

'l:eX~:DoOk

us uf

i

14.7 Aggregation

l.nt.orma"t.i.on:

Title: Starting Out with CH "",,,thor:

G ... dd.i.~

Publisher: Addison- wesley

Yo

Aggregation in UML Diagrams

az

In Chapter 13 you were introduced to the Unified Modeling Language (UML) as a cool for designing classes. You show aggregation in a UML diagram by connecting two classes with a line thar has an open diamond at one end. The diamond is closest to the class that is the aggregate. Figure 14-5 shows a UML diagram depicting the relationship between the Course, Instructor, and TextBook classes. The open diamond is closest to the Course class because it is the aggregate (the whole).

Ri

Figure 14-5

an

Course

ss

- courseName : char [J - instructor : Instructor - textBook: TextBook

+ Course(name : char 0, instr : &Instructor,

text: &TextBook) :

0

ad

Ha

+ printO : void

m

Instructor

m

- laslName : char [ 1 - lirstName : char [ I - officeNumber : char [ J + InSlructor{lname: char', fname: char ' ,

- tille : char [ 1 - author: char [ I - publisher : char [ I + TexlBook(texlTitle : char', auth : char 路 ,

pub: char 0) :

+ Te'tBook(obj: &Te,tBook) : + set(textTitle : char', auth : char ' , pub : char 0) : void

+ prinlO ; void

M

uh a

office: char *) : + Instructor(obj ; &Instructor) : + set(lname : char ' , fname : char 0, office: char oJ : void + printO : void

TextBook

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 14

More About Classes

i

878

us uf

Focus on Object-Oriented Design: Class Collaborations

Yo

CONCEPT: It is common for classes to in teract, or collaborate, with one anoth er to perform their operations. Part of the o bject-oriented design process is id entifying tbe collabora tions between classes.

az

In an object-o ri ented application it is common for objects of different cl asses to collabora te, This simpl y means that objects interact with each other. Some times one ob ject will need the services of another object in order ro fulfill its responsibi lities. For example, let's sayan o bject needs to read a number from the keyboard and then fo rm at t he number ro

Ri

appear as a dollar amo un t. The object might use the services of the cin o bj ect to read the numbe r from the keyboard, and then use the services of a nother object that is designed to forma t the nu mber.

If one o bject is to collaborate with another object, then it must know somethi ng about the other o bject's member functions and how to call them. Let's look at an example.

Ha

ss

an

The fo llowing code shows a class named Stock. An object of this class holds data a bout a company-s sroc k. This cla ss has twO attri butes: symbol and sharePrice. The symbol attribute holds the tradi.ng symbol for the compa ny's stock. Thi s is a shorr series of charactefS that are used to identify the srock on the stock exchange. For example, the X YZ Company's stock might have the trading symbol XYZ. T he sharePrice attribute holds the current price per share of the stock. The class also has the fo llowing member functions: A default constructor that initia lizes symbol to an empty string and sharePrice

to 0.0. A conStructor t hat accepts a rguments for the symbol and share price. A copy constructo r A set function that accepts arguments for the symbol and share price. A getSymbol fu nction that returns the stoc k's trading sym bo l. A getSharePrice fu nction that returns the current price of the stock.

• •

ad

m

• •

Contents of Stock . h 1

'ifndef STOel( 'define STOCK 'i ncl ude <cstri ng >

m

2

3

4

uh a

5 6

II Constant for symbol arra y. canst int SYMBOL SIZE ~ 6;

7

8

class Stock

M

9

10 11

12

private : c har symbOl[SYMBOL_S IZEI; II Trading symbo ~ o f the stock double sharePrice; II Current pric e per share

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 8 79

14 15 16

public: II Default Constructor Stock() ( set("", 0 . 0); }

us uf

13

i

14.8 Focus on Object-Oriented Design: Class Collaborations

II Constructor Stock(const char .sym, double price) ( set(sym, price); }

18 19

20 21

// Mutator function void set(const char *sym, ( strncpy(symbol, sym, symbo![SYMBOL_SIZE sharePrice = price;

27

28 29 30 31 32

}

an

34 35

double getSharePrice() const { return sharePrice ; }

36 37

}: lendif

ss

39

1] = '\0':

/1 Accessor functions canst char *getSymbol() const { return symbol; }

33

38

double price) SYMBOL SIZE):

Ri

24 25 26

az

/1 Copy constructor Stock(const Stock &obj) ( set (obj . symbol, obj . sharePrice); }

22

23

Yo

17

ad

Ha

The following code shows another class named StockPurchase chac uses an object of the Stock class to simulate the purchase of a stock. The StockPurchase class is responsible for calculati ng the cost of the srock purchase. To do that, the StockPurchase class must know how to call the Stock class's getSharePrice function to get the price per share of the srock.

Contents of StockPurchase. h 1

lifndef STOCK PURCHASE #define STOCK_PURCHASE 'include "Stock. h路'

m

2

3

4

class StockPurchase

7 8

private: Stock stock; 1/ The stock that was purchased int shares; 1/ The number of shares pUblic: II The default constructor sets shares to O. The stock II object is initialized by its default constructor. StockPurchase() { shares - 0; }

uh a

m

5 6

9

10 11

M

12 13 14

(

15

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH More About Classes

i

Chapter 14

II constructor

17

StockPurchase(const Stock &stockObject, in t numShares)

18

{ stock

19

shares

20 21 22 23 24 25

~

stockObject;

= numSharesi

}

II Accessor function double getCost{) canst { return shares * stock . getSharePrice()i }

us uf

16

Yo

880

); 'endif

Ri

az

Th e second constructor for the StockPurchase class accepts a Stock object representing the stock that is being purchased, and an int representing the number of shares to purchase. In line 18 we see the first collaboration: the StockPurchase conStructor makes a copy of the Stock object by using the Stock class's copy constructor. The next collabora tion takes place in the getCost function. This function calculates and returns the cost of the stOck purchase. In line 23 it calls (he Stock class's getSharePrice function to determine the stock's price per share. Program 14-16 demonsuares this class.

II Stock trader program

2 3 4 5

iinclude <iost ream> 'include <iomanip> iinclude "Stock.h" tinclude "StockPurchase . h'· using namespace std;

6

int main()

9

{

10

int sharesToBuy;

11

II Number of shares to buy

II Create a Stock object for the company stock. The II trading symbol is XYZ and the stock is currently

14 15

JI priced at $9.62 per share. Stock xyzCompany("XYZ", 9.62);

19

uh a

20 21 22 23

JI Display the symbol and current share price. cout « setprecision(2) « fixed « Showpoint; cout « "XYZ Company ' s trading symbol is « xyzCompany.getSymbol() « endl; cout « "The stock is cu r rently $" « xyzCompany.getSharePrice() « .. per share. \n" ;

m

"17 18

ad

13

m

12

Ha

7

8

ss

1

an

Program 14-16

24 25

26

M

27 28

JI Get the number of shares to purchase . cout « "How many shares do you want to buy? "; cin » sharesToBuYi

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14.8 Focus on Object-Oriented Design: Class Collaborations

33 34

35 36

II Display the cost of the transaction . COllt « "The cost of the transaction is $" « buy.getCost() « endl;

return 0;

i us uf

32

II Create a StockPurchase object for the transaction . StockPurchase buy(xyzCompany, sharesToBuy);

Yo

29 30 31

881

az

Program Output with Example Input Shown In Bold XYZ Company's trading symbol is XYZ The stock is currently $9.62 per share . How many shares do you want to buy? 100 [Enter] The cost of the transaction is $962.00

Ri

Determining Class Collaborations with CRC Cards

the things that the class is responsible for knowing the actions that the class is responsible for doing

ss

• •

an

During the object-oriented design process, you can determine many of the collaborations that wil l be necessary between classes by examIning the responsibilities of the classes. In Chapter 13 we discussed the process of finding the classes and their respons ibilities. Recall from that section [hat a class's responsibilities are

Ha

Often you will determine that the class must collaborate with another class in order to fu lfill one or more of its responsibilities. One popular method of discovering a class's responsibilities and collaborations is by creating CRC cards. eRG stands for class, responsibilities, and collaborations.

m

ad

You can use simple index cards for this procedure. Once you have gone throllgh the process of finding the classes (which is discussed in Chapter 13), set aside one index ca rd for each class. At the top of the index card, write the name of the class. Divide the rest o f the card into two columns. In the leEr colu mn, write each of the class's responsibilities. As yOll write each responsibility, think about whether the class needs to collaborate with another class to fulfill that responsibility. Ask yourself questions such as •

m

Will an ob ject of this class need ro get data from another object in order to fulfill this responsibility? Will an o bjecr o f this class need co request another object co perform an operation in order to fulflll this responsibility?

uh a

If collaboration is required, write the name of rhe collaborating class in (he right column, next to the responsibi lity that requires it. If no collaboration is required for a responsibil · ity, simply write "None" in the right column, or leave it blank. Figure 14-6 shows an

eRe card for the StockPurchMe class.

M

example

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 882

More About Classes

i

Chapter 14

us uf

Figure 14-6 Name of the class

...... 5tockPurchasB

Know the etOGk to

St ock class

purc;nase

Responsibilities {

Know the number of shares

to pUrGhas6

Calculate the cost of

couaboratin g

None

}

classes

Stock class

az

the pUr'(;has6

Yo

'"

Ri

From {he eRe card shown in the figure, we can see that the StockPurhcase class has the following responsib ilities and col laborations: •

Responsibi liry : To know the stock to purchase Colla boration: The Stock class Responsibility: To know the number of shares [0 purchase Collaboration: None

an

• •

Responsibility: To calculate t he

COSt

of the purchase

Collaboration : The Stock class

14.31 14.32

Ha

~ Checkpoint

ss

When you have com pleted a eRe card for each class in the appl ica tion, you will have a good idea of each class's responsibilities and how the cl asses must interact.

What a re the benefits of having operaror functions that perform object conversion? Wh y are no return types listed in the protOtypes or headers of operator fu nctions that perform data type conversion? Assume there is a class named BlackBox. Write the header fo r a member funct ion tha t conven s a BlackBox object [Q an into

14.34

Assume there are two classes J Big a nd Small. T he Big class has, as a member, an instance of (he Small class. Wr ite a sentence tha t describes the rel ationsh ip between the two classes.

M

uh a

m

m

ad

14.33

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 883

i

Review Questions and E.xercises

us uf

Review Questions and Exercises Short Answer

1. Describe the difference between an instance member variable and a static member variable.

Yo

2. Assume that a class named Numbers has the following static member function declaration: static void showTotal()i Write a statement that calls the showTotal function.

az

3. A static member variable is declared in a class. Where is the static member variable defined? 4. What is a friend function? 6. What is memberwise assignment?

7. When is a copy constructor called?

Ri

5. Why is it not always a good idea to ma ke an entire class a friend of another class?

an

8. How can the compiler determine if a constructor is a copy constructor?

9. Describe a situation where memberwise assignment is not desirable. 10. Why muSt the parameter of a copy constructor be a reference?

ss

11. What is a defau lt copy constructor?

13. What is passed

Ha

12. Why would a programmer want to overload operators rather than use regular member functions to perform similar operations? to

the parameter of a class's operator= function?

14. Why shouldn't a class's overloaded == operator be implemented with a void operator

function?

15. How does the compiler know whether an overloaded ++ operator should be used in

ad

prefix or postfix mode? 16. What is the this pointer?

m

17. What type of value should be returned from an overloaded relational operator function?

m

18. The class Stuff has both a copy constructor and an overloaded,", operator. Assume

M

uh a

that blob and clump are both instances of the Stuff class. For each statement below, indicate whether the copy constr uctor or the overloaded .. operator will be called. Stuff blob = clump; clump == blob; blob.operator~(clump);

showValues(blob);

II blob is passed by value.

19. Explain the programming steps necessary

to

make a class's member variable static.

20. Explain the programming steps necessary

to

make a class's member function static.

21. Consider the following class declaration: class Thing {

private: int x;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH More About Classes

i

Chapter 14

,

{ z = a; }

Yo

)

us uf

int y; static int z; public: Thing( ) {x=y=z;} static void putThing(int a)

Assume a program containing the class declaration defines three Thing objects with the following statement: Thing one, two, three; How many separate instances of the x member exist?

az

How many separate instances of the y member exist? How many separate instances of the z member exist? What va lue will be stored in the x and y members of each object?

Ri

Write a statement that will call the putThing member function before the objects above are defined.

an

22. Describe the difference between making a class a member of another class (object aggregation), and making a class a friend of another class. 23. What is the purpose of a forward declaration of a class?

ss

24. Explain why memberwise assignment can cause problems with a class that conrains a pointer member.

Fill-in-the-Blank

Ha

25. Why is a class's copy constructor called when an object of that class is passed by value into a function?

26. If a member variable is declared _____ , all objects of that class have access to the same variable.

ad

27. Static member variables are defined _ _ _ _ the class. 28. A(n) _-,___ member function cannot access any nonstatic member variables in its own class.

m

29. A static member function may be called _ _ _ _ any instances of its class are defined.

m

30. A(n) function is not a member of a class, but has access to the private members of the class.

uh a

31. A(n) _____ tells the compiler that a specific class will be declared later in the program.

M

32.

is the default behavior when an object is assigned the value of another object of the same class.

33. A(n) is a special constructor, called whenever a new object is initialized with another object's data. 34.

is a special built-in pointer that is automatically passed as a hidden argument to all nonstatic member functions.

35. An operator may be _ _ _ _ to work with a specific class.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

-


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

us uf

36 . When overloadi ng the _____ operator, its function must have a dummy parameter.

885

37. Making an instance of one class a member of another class is called _____.

38. Object aggregation is useful for creating a(n) _____ rel ationsh ip between two classes.

Yo

Algorithm Workbench

39. Assume a class named Bird exists. Write the header for a member funct ion that overloads the

=

opera tor for that class.

az

40. Assume a class named Dollars exists. Write the headers for member funct ions that overload the prefix and postfix ++ operators for that class. 41. Assume a class named Yen exists. Write the header for a member function that overloads the < operator for that class.

Ri

42. Assume a class named Length exists. Write the header for a member fu nction that overloads cout's ÂŤ operator for that class.

an

43. Assu me a class named Collection exists. Write the header fo r a member function that overloads the [ 1 operatOr for that class.

True or False F

Static member variables can not be accessed by nonstatic member functions.

45. T 46. T

F

Static member variables are defined outside their class declaration.

F

A static member funct ion may refer to nonstatic member variables of the same

ss

44. T

Ha

class, but only after an instance of the class has been defined. F

When a function is declared a friend by a class, it becomes a member of that class.

48. T

F

A friend function has access to the private members of the class declaring it a friend.

49. T

F

An entire class may be declared a friend of another class.

50. T

F

ad

47. T

m

In order for a funct ion or class to become a friend of another class, it must be declared as such by the class granting it access. If a class has a pointer as a member, it's a good idea to also have a copy constmctor.

F

52. T

F

You ca nnot use the =operator to assign one object's values to another object, unless you overload the operator.

53. T

F

If a class doesn't have a copy constructor, the compiler generates a default copy constructor for it.

54. T

F

55. T 56. T

F

IJ a class has a copy constructor, and an object of that class is passed by value into a function, the function's parameter will not call its copy constructor. The this pointer is passed to static member functions.

F

All functions that overload unary operators must have a dummy parameter.

57. T

F

For an object to perform automatic type conversion, an operator function must

M

uh a

m

51. T

be written. 58. T

F

It is possible to have an instance of one class as a member of another class.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH More About Classes

i

Chapter 14

886

us uf

Find the Error

Each of rhe following class declarations has errors. Locate as many as you ca n. 59. class Box {

double width; double length; double height; public : Box(doub i e w, 1, h) { width:

length = 1; height

Wi

~

hi

}

Yo

private :

}

Other member functions follow

,

)

= b . widthi = b.length ; = b . height;

Ri

{ width l ength height

az

Box{Box b) II Copy constructor

60. class Ci rcle private :

ss

double diameter: lot centerX; int centerYi

an

{

public :

y, )

Ha

Circle(double ct, int x, int y) { diameter = d ; centerX = X i centerY /1 Overloaded

operator vold Circle=(Circle &right) diameter = r i ght.diameter ; =

centerX

~

right . centerX ;

centerY

=

right . centerY; }

.. . Other member functions follow

ad )

,

{

m

61. class Point

m

private:

iot :xCoord ; int yCoord ;

M

uh a

public:

Point (int x, int y) { xCoord ~ Xi yCoord = y ; } II Overloaded + operator void opcrator+(const &Point right) { xCoord += right . xCoord ; yCoord += r i ght.yCoord ; }

)

,

Other member functions follow ...

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

887

i

Review Questions and Exercises

us uf

62. class Box

Ri

Other member functions f o llow

az

private : double width; double length; double height; public : Box(doub1e w, 1, h) { width = w; length = 1; height - h; } II Overloaded prefix ++ operator void operator++() { ++width; ++length; } II Overloaded postfix ++ operator void operator++() { width++ i 1ength++ ; }

Yo

{

) ;

63. class Yard

Ha

ss

an

private : float length; public: yard(float 1) { length = 1; } 1/ f loa t conversion function void operator float() { return length; }

Other member functions follow . . . ) ;

Programming Challenges

ad

1. Numbe r s Class

m

m

Design a class Numbers that can be used to translate whole dolla r amou nts in the range 0 through 9999 inro an English description of the number. For example, the number 713 wou ld be translated into the string seven hundred thirteen, and 8203 wOllld be translated into eight thousand two hundred three. The cla ss sho uld have a single integer member variab le: int number;

<l sta tic array of strings that specify how to translate key dollar amounts into the desired fo rmat. For example, you might use static strings such as

uh a

and

M

char lessThan20(20)[25] = {"zero·', "one·' , ... , ··eighteen", ·' nineteen"}; char hundred[ 1 - ·'hundred"; char thousand[ 1 '" "thousand";

The class should have a constnlcCOr that accepts a nonnegative integer and uses it to initialize the Numbers object. It should have a member function print() that prints the English description of the Numbers object. D emonstrate the class b y writin.s a main program [hat asks the use r ro enter a number in the proper range and then prmts (Jut its English description .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH More Abou t Classes

i

Chapter 14

888

us uf

2. Day of the Year

Assuming that a year has 365 days, write a class named DayOfYear that takes an integer representing a day of the year and translates it to a string consisting of the month followed by day of the month. For example,

Yo

Day 2 would be January 2. Day 32 would be February 1. Day 365 would be December 31.

az

The conStructor for the class should take as parameter an integer representi ng the day of the year, and the class should have a member funct ion print ( ) that prints the day in the month-day format. The class should have an integer member variable to represent the day, and should have static member va riables holding strings that can be used to assist in the translation from the integer format to the monch-day format.

Ri

Test your class by inputting: various integers representing days and printing out their representation in the month-day format.

3. Day of the Year Modification

ss

an

Modify the DayOfYear class, written in Programming Cha llenge 2, to add a construcror that takes twO parameters: a string representing a month and an integer in the range 0 through 31 representing the day of the month. The constructor should then initialize the integer member of the class ro represent the day specified by the month and day of month parameters. The constructor should terminate the program with an appropriate error message if the number entered for a day is outside the range of days for the month given.

++

Ha

Add the following overloaded operarors:

prefix and postfix increment operators. These operators should modify the object so that it represents the next day. If the day is a';eady the end of the year, the new value of the object will represent the first day of the year.

DayOfYear

ad

prefix and postfix decrement operators. These operators should modify the DayOfYear object so that it represents the p revious day. If the day is already the

first day of the yeat, the new value of the object will teptesent the last day of the 4.

m

year. NumDays

Class

uh a

m

Design a class called NumDays. The class's purpose is to store a value that represents a number of work hours and convert it to a number of days. For example, 8 hours would be converted to 1 day, 12 hours would be converted to 1.5 days, and 18 hours would be converted to 2.25 days. The class should have a constructor that accepts a number of hours, as well as member functions for storing and retrieving the hours and days. The class should also have the following overloaded operators:

Solving the NumDays

Problem

M

+

Addition operator. When twO NumDays objects are added together, the overloaded + operator should return the sum of [he two objects' hours members. Subtraction operator. When one NumDays objecr is subtracted from another, the overloaded - operator should return the difference of the two objects' hours members.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Prefix aud postfix increment operat number of hours stored the obJ路ecr

in

ShOUJd be automatically recalculated.

Th

us uf

i

Review Questions and E.xercises

o;h ~se operators should increment the . en Incremented the num ber of d '

ays

Prefix mrd post/lx decremeltt operators. These operators should decrement the

number of hours scored in the objea. When decremented) [he number of days

Yo

should be automatically recakulated.

5. Time Off

az

( ) L _N_O_T_E_:_T_,_,,_,_._'_,_ig_n_"_,e_n_t_,_,_,_u_m_,_,_'_0_'_'_h_.v_e_ , _,,_e_.d_, _c_o_m_p_,_e_te_d_P_w_g_,_,_m_m _ in_g_C_h_,_"_e_n_g_e_4_,..-J

Ri

Design a class named TimeOff. The purpose of the class is to track an employee's sick leave, vacation, and unpaid time off. It should have, as members, the follow ing instances of the NumOays class described in Programming Challenge 4:

A NumDays object that records the maximum number of days of

sickTaken

sick leave the employee may rakc. A NUmDays object that records the number of days of sick leave the employee has already taken.

maxVacation

A NumDoys object that records the maximum number of days o f

an

maxsickoays

paid vacation the employee may take.

Ha

maxUnpaid unpaidTaken

A NumOays object that records the number of days of paid vacation the employee has already taken. A NumDays object chat records the maximum number of days of unpaid vacation the employee may take.

ss

vacTaken

A NumDays object that records the number of days of unpaid leave the employee has taken.

ad

Additionally, the class should have members for hold ing the employee's name and identification number. It shou ld have an appropriate constructor and member functions for storing and rctrieving data in any of the member objects.

m

Input Validation: Company policy states that an employee may not accumulate more than 240 hours of paid vacation. The class should not allow the maxVacation object to store a value greater than this amount.

..A

m

6. Personnel Report

NOTE: This assignment assumes you have already completed Programming

M

uh a

~ LChallenges 4 and 5. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -_ _ _ _ __

~

Write a program that uses an instance of the TimeOff class you designed in Programming Challenge S. The program should ask the user to enter the number of months an employee has worked for the company. It should [hen use the TimgOff object to calculate and display the employee's maximum number of sick leave and vacation days . Employees earn 12 hours of vacation leave and 8 hours of sick leave per month.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

869


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

More About Classes

7. Month C lass

us uf

Chapter 14

890

Design a class named Month. The class should have the following pr ivate members:

name A string object that holds the name of a month, slich as "Janu a ry," "Februa ry, " etc.

monthNumber

An integer

variable that holds the number

of

the month. For

In addition, provide the following member functions:

Yo

example, January would be 1, Febnlary would be 2, erc. Valid values for this variable a re :I through 12.

az

A default constructor that sets monthNumber to 1 and name [0 "Janllary." A consrrucror that accepts the name of the month as an J rgument. It should set name to rhe value passed as the argument and set monthNumber to the co rrect

value.

Ri

A conSffllCtor thcH accepts the number of the month as an argument, It should set monthNumber ro the vallie passed as the argument and ser name to the correct month name. Appropr iate set and get functions for the name and monthNumber member variables. Prefix and postfix overloaded ++ operator funcrions that increment monthNumber and set name ro the name of next month. If monthNumber is set to 12 when tltest: functions execute, they should set monthNumber ro 1 and name to "January." Prefix and postfix overloaded -- operator functions that decrement month Number and set name to [he name of previous month. If monthNumber is set to 1 when these fu nctions execute, rhey should set monthNumber to 12 and name to "December."

an

Ha

ss

Also, you should overload cout's« operator and cin's» operator to work with the Month class. Demonstrate the class in a program.

8. Da t e Cl ass Modifica tion

Prefix and postfix il1cremwt operators, T hese operators should inc remenr rhe object's day member. Pre fix a lld postfix decrement operators. These operawrs should decrement the objecr's day member.

uh a

m

m

++

ad

Modify the Date class in Programming Challenge 1 of Chapter 13. T he new version should have the followi ng overloaded operators:

«

M

»

Subtracti01~

operator. If one Date object is subtracted from anorher, the operaror should give rhe number of days between the two dates. Fo r example, if April '10,

2009 is subtracted from April 18,2009, the result will be 8. cout's stream insertioll operator. This operator should cause the dare to be displayed in the form April 18, 2009 cin's stream extraction operator. This operator should prompt the user for a date to be stored in a Date object.

The class shou ld detect the fol lowing cond itions and handle them accordingly:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 891

• •

us uf

When a date is set to the last day of the month and incremented, it should become the first day of the following momh, When a date is set to December 31 and incremented, it should become Jan uary 1 of the following year. When a day is set to the first day of the month and decremented, it should become the last day of the previous month. When a date is set to January 1 and decremented, it should become December 31 of the previous year.

Demonstrate the class's capab"ilitTes in a simple program,

Yo

i

Review Questions and Exercises

~ ~~

az

Input Validation: The overloaded » operator should not accept invalid dates. For example, the date 13/45/09 should not be accepted. 9. FeetInches Modification

Ri

Modify the FeetInches class discussed in th is chapter so it overloads the following operators: <=

>=

an

1=

Demonstrate the class's capabilities in a simple program. 10. Corporate Sales

m

m

An array with four elements for holding four quarters of sa les figures for the division. A private static variable for holding the total corporate sa les for all divisions for the entire year. A member funct ion that takes four arguments, each assumed to be the sa les for a Quarter. The val ue of the arguments should be copied into the array that holds the sales data. T he total of the four arguments should be added to the static variable tha t ho lds the total yearly corporate sales. A function that takes an integer argument within the range of 0-3. T he argument is ro be used as a sLlbscri pt into the division Quarterly sales array. The function sho uld return the value of the array element with that subscript.

ad

• •

Ha

ss

A corporation has six divisions, each responsible for sales to different geographic locations. Design a DivSales class that keeps sales data for a division, with the fo llowing members:

uh a

Write a program that creates an array of six DivSales objects. The program should ask the user ro enter the sales for four quarters for each division. After the data are entered, the program should display a table showing the division sales for each quarter. The program shou ld then display the total corporate sa les for the year.

Input Validation: Only accept positive values for quarterly sales figures.

M

11. FeetInches Class Copy Constructor and multiply Function Add a copy constructo r to the FeetInches class. This constructor should accept a FeetInches object as an argument. The constructor should assign ro the feet attribute the val ue in the argument's feet attribute, and assign to the inches attribute the va lue in the argument's inches attribute. As a result, the new object will be a copy of the argument object.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 14

More About Classes

i

892

us uf

Next, add a multiply member function to the Feetlnches cbss. The multiply function shou ld accept a Feetlnches object as an argument. The argumcnr objen's feet a nd inches attributes will be multiplied by (he calli ng object's feet and inches attributes, and a Feetlnches object containi ng the result will be returned.

12. LandTract Class

Yo

Make a LandTract class that is composed of twO Feetlnches objects, one for the tract's length and one for the width. The class should have a member function that rerurns the tract's area. Demonstrate the class in a program that asks the user to enter the dimensions fo r twO tracts of land. The program shou ld d isplay the area of each tract of land and ind icate whether the tracts arc of equal size.

az

13. Carpet Calcul ator

Ri

The Wesrfield Carpet Compa ny has asked you ro write an application that calcu lates the price of carpeti ng for rectangula r rooms. To calculate the price, you multiply the area of the floor (width times length) by the price per square foot of carpet. For example, the area of floor that is 12 feet long and 10 feet wide is 120 square feet. To cover that floo r with carpet that costs $8 per square foot wou ld cost $960. (12 x 10 x 8 =960.)

Ha

ss

an

First, you sho uld create a class named RoomDimension that has twO FeetInches objects as attri butes: one for the length of the room and one fo r the width. (You should use the version of the Feetlnches class that you created in Programming Challenge 11 with the addition of a multiply member function. You can use th is fun ction to calculate the area of the room.) The RoomDimension class should have a member function that returns the area of the room as a FeetInches object. Next, you should create a RoomCarpet class that has a RoomDimension object as an attribute. It should also have an attribure for the COSt of the ca rper per square foot. The RoomCarpet class shou ld have a member function that returns the rotal cost of the carpet .

ad

Once yOLl have written these classes, use them in a n appl ication that asks the user to enter the dimensions of a room and the price per square foot of the desired carpeting. The appl ication should display the total COSt of the carper.

m

14. Parki ng Ticket Simulator

m

For this assignment you will design a set of classes that work together to simulate a police officer issuing a parking [icket. The classes yo u should design are:

uh a

â&#x20AC;˘

M

â&#x20AC;˘

The ParkedCar Class: This class should simulate a parked car. The class's responsibilities are: To know the car's make, model, color, license number, and the number of minutes that the ca r has been parked The ParkingMeter Class: This class should simu late a parking meter. The class's on ly responsib ility is: To know rhe number of minutes of parking rime that has been purchased

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises

i

us uf

Ri

az

The ParkingTicket Class: This class should simulate a parking ticket. The class's responsibi lifies are: To report the make, model, color, and license number of th e illegally parked car To report the amount of the fine, which is $25 for the first hour or part of an hour that the car is illegally parked , plus $10 for every additiona l hour or parr of an hour that the ca r is illegally parked To report the name and badge numbe r of the police officer issui ng the ticket The PoliceOffieer Class: This class should simu la te a police office r inspecting pa rked cars. The class's responsi bilities are: To know the police officer's name and badge number To examine a ParkedCar object and a parkingMeter object, and determine whether tbe car's time has expired To iss ue a parking ticker (generate a ParkingTicket object) if the car's time has expired

Yo

893

Write a program that demonstrates how these classes collaborate.

15. Car Insfrumem Simularor

an

for this assignment you will design a set of classes that work together to simulate a car's fue l gange and odometer. The classes yOll will design arc: T he FuelGauge Class: This class will simulate a fucl gauge. Its responsibilities ace To know the car's current amount of fuel, in gallons. To report the car's current arnounr of fuel, in ga llons. To be able to increment the amount of fu el by 1 gallon. This simulates purring fuel in the car. (The car can hold a maximum of 15 gallons.) To be able to decrement the amount o f fuel by 1 gallon, if the amount of fue l is greater than 0 gal lons. This simulates burning fuel as rhe car runs.

The Odometer Class: Tbis class will simulate the ca r's odometer. Its responsibi li ties arc: To know the car's current mi leage. To report the car's current mileage. To be able to increment the current mileage by 1 mile. The maximum mileage the odometer can Store is 999,999 miles. When this amount is exceeded, the odometer resets the current mileage to O. To be able to work with a FuelGuage object. It should decrease the FuelGauge object's current amount of fu el by 1 gallon for every 24 miles traveled. (The ca r's fue l economy is 24 miles per gallon.)

uh a

m

m

ad

Ha

ss

M

Demonstrate the classes by creating instances of each. Simu late fi lling the car up with fuel, and then run a loop that increments the odometer umil the ca r runs out of fuel. During each loop iteration, print the car's cu rrent mileage and amOllnr of fuel.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH More About Classes

1. Add the bookMatch Member Function to the BookData Class

us uf

Serendipity Booksellers Software Development ProJectPart 14: A Problem-Solving Exercise

i

Chapter 14

894

Cu rrently the functions lookUpBook, edit Book, and deleteBook search the book database for titles that match, or partially match, a search string. Add a member func-

Yo

tio n na med bookMatch to the BookOata class. The fun ction should accept a string as its argument and return true if the string is found in the book title. If the string is nOt found in the book tide, bookMatch should return false.

2. Modify lookUpBook, edi tBook, and deleteBook

az

Currently the lookUpBook, editBook, and deleteBook fu nctions have their own method of comparing book titles with search strings. Modify them so [hey use the bookMatch function you added to the BookData class in Step 1.

Ri

3. Modify the Report Module

The reporting capabi lities you added in Chapter 9 must now be modified to work with the BookData class.

an

4. Add Other Classes to the Program Analyze the program for other ways to implement classes. Here are some suggestions: Consider whether the various menus could be managed by class objects. Could a class be constructed to hand le the program's user interface? Analyze the file I/O performed by the program. Could a class be constructed to handle all the file operations? Determine if input validation could be performed by a class object.

ss

• •

M

uh a

m

m

ad

Ha

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


15.2

15.3

15.7

15.8

Polymorp hism and Virtual Member Functions Abstract Base Classes and Pure Virtual Functions Mult iple Inheritance

Ha

ss

15.4 15.5

15.6

an

What Is Inheri tance? Protected Mem bers and Cl ass Access Constructors and Destructors in Base and Derived Classes Redefining Base Class Functions Class Hierarchies

15.1

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

What Is Inheritance?

ad

CONCEPT: Inheritance allows a new class to be based on an existing class. T he new

m

class inhe rits a U th e m e m ber variables a nd fun ct ions (except t he const ru cto rs and destr uctor) of the class it is based on.

Generalization and Specialization

m

In rhe rea! world you ca n find many objects that are specialized versions of other more general objects. For example, the term "insect " describes a very general type of creature with numerous characteristics. Because grasshoppers and bum blebees are insects, they

uh a

have all the general characteristics of an insect. In addition, (hey have speci al characteristics of their own. For exa mple, the grasshopper has its jumping a bility, and the bumblebee has its stinger. Grasshoppers and bumblebees are specia lized versions of an insect. Th is is

M

illustrated in Figure 15路1.

895

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

Inheritance, Polymorphism, and Virtual Functions

Yo

All insects have certain characteristics.

us uf

i

Figure 15-1

In addtion to the common insect characteristics, the grasshopper has its own unique characteristics such as the ability 10 jump.

Ri

az

In addition to the common insect characteristics, the bumble bee has its own unique characteristics such as the ability to sling.

Inheritance and the uls aU Relationship

the " is a" relations hip.

ss

• • •

A poodle is a dog. A car is a vebicle. A tree is a plant. A rectangle is a shape. A football player is an athlete.

Ha

an

When one object is a specialized version of another object, there is an "is a" relationship between them. For example, a grasshopper is an msect. Here are a few other examples of

When an "is a" relations hip exists between classes, it means that the specialized class has

ad

all of the characteristics of the general class, plus additional characteristics that make it special. 111 object-oriented programming, inheritance is used to create all "is a" relation -

ship between classes.

m

m

Inheritance involves a base class and a derived class . T he base class is rhe general class and the derived class is the specialized class. T he derived class is based on, or derived from, the base class. You ca n think of the base class as the parent and the derived class as the child. This is illustrated in Figure 15-2.

uh a

Figure 15-2

M

896

Insect class

members

Base Class (Parent)

Grasshopper class

members

Derived Class (Child)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 897

i

15.1 What Is Inheritance?

us uf

T he derived class inherits the member variables and member functions of the base class without any of them being rewritten. Furthe rmore. new member variables and functions may be added to the derived class to make it more specialized than the base class.

az

Yo

Lee's look at an example of how inheritance can be used . Most teachers assign variolls graded activities for their studenrs to complete. A graded activity can receive a numeric score such as 70, 85, 90, and so on, and a letter grade such as A, B, C, D, Or F. The following GradedActivity class is designed ro hold the numeric score a nd letter grade of a graded activity. When a numeric sco re is stored by the class, it automatically determines the letter grade. (These files are stored in the Student Source Code Folder Chapter 15\ GradedActivity version 1.)

Contents of GradedActivity . h (Version 1)

4

lifndef GRADEDACTIVITY H 'define GRADEDACTIV!TY H

Ri

1 2 3

II GradedActivity class declaration

5

6

class Gr adedActivity {

8

private : double scoce ; II To hold the numecic scoce public: II Default constructor GradedActivity() { score'" 0 . 0; }

13 14

ss

12

Ha

9 10 11

an

7

/1 Constructor GradedActivity(double s) {score=s;}

15

16 17

18

1/ Mutator function

void setScore( double s)

ad

19

20

{ score - Si }

21 22

II Accessor functions double getScore() const { return score; }

m

23 24 25 26

char getLetterGrade(} canst;

}i

29

'endif

uh a

m

27 28

Contents of GradedActi vity . cpp (Version 1) 1

linclude "GradedActivity . h "

M

2

3 4

/1*************************************** ************* * * â&#x20AC;˘ // Member function GradedActivity :: getLetterGrade

6

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Inheritance, Polymorphism, and Virtual Functions

7 8

char GradedActivity : : getLetterGrade() canst {

i

Chapter 15

char letterGrade; II To hold the letter grade

9

10 i f (score > 89)

12 13 14 15 16

letterGrade else if (score letterGrade else i f (score

'A' i

79) '8' ;

69)

letterGrade 'c' ; else i f (score > 59) letterGrade 'D' ;

17 18 19 20 21 22

else 'F';

az

letterGrade =

return letterGrade;

}

Ri

23

= > = >

Yo

11

us uf

898

The GradedActivity class has a default constructor that initializes the score member var iable to 0.0. A second conStructor accepts an argument for score. The setScore member function also accepts an argument for the score variable, and the getLetterGrade

an

member fu nction returns the letter grade that correspo nds to the value in score. Program 15-1 demonstrates the GradedActivity class. (This file is also stored in the Student Source Code Folder Chapter 15 \GradedActivity Version 1.)

3 4

II This proqram demons t rates the GradedActivity class. 'include <iostream> 'include "GradedActivity . h" using namespace std;

Ha

1 2

ss

Program 15-1

5

6 7

int main() {

8

10

II Cre a te a GradedActivity object for the test_ GradedActivity test;

m

11 12

II Display the letter grade for the test . cout « "The grade for th a t test is " « test . getLetterGrade() « endl;

M

22 23 24

II Store the numeric score in the test object _ test . setScore(testScore);

uh a

20 21

II Get a numeric test score from the user. cout « "Enter your numeric test score : " ; cin » testScorei

m

13 14 15 16 17 18 19

25

II To hold a test score

ad

double testScore;

9

return 0;

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15. 1 What Is Inheritance?

i

899

Yo

Program Output with Different Example Input Shown In Bold Enter your numeric test score: 75 [Enter] The grade for that test is C

us uf

Program Output with Example Input Shown In Bold Enter your numeric test score : 89 [Enter] The grade for that test is B

Contents of F inalEx am . h

5 6 7

â&#x20AC;˘ 9

10 11

12

class FinalExam : public GradedActivity { private : int numQuestions; // Number of questions double pointsEach; // Points for each question int numMissed; 1/ Number of questions missed public: II Defau lt constructor FinalExam() { numQuestions = 0; pointsEach ~ 0 . 0; numMissed = 0 ; }

m

13 14 15 16

ss

3

Ha

,

#ifndef FINALEXAM H 'define FINALEXAM H hnclude "GradedActivity.h"

ad

1 2

an

Ri

az

The GradedActivi ty class represents the general characteristics of a student's graded activity. Many different types of graded activities exist, however, such as quizzes, midterm exams, final exams, lab reports, essays, and so on. Because the numeric scores might be determined differently for each of these graded activities, we can create derived classes to handle each one. For example, the following code shows the FinalExam class, which is derived from the GradedActivity class. It has member variables for the number of questions on the exa m (numQuestions), the number of points each question is worrh (points Each ), and the number of questions missed by the srudem (numM issed ). These files are also stored in the Student Source Code Folder Chapter lS\GradedActivity Version 1.

17

uh a

m

18 19 20 21 22 23

II Constructor FinalExam{int questions, int missed) ( set (questions , missed); }

II Mutator function void set(int, int I;

1/ Defined in FinalExam,cpp

24

M

25 26 27

II Accessor functions double getNumQuestions() const { return numQuestions; }

2. 29 30

double getPointsEach() const { return pointsEachj }

31

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Inheritance, Polymorphism, and Virtual Functions

iot getNUmMissed() const { return numMissed; }

34

i

32 33

us uf

Chapter 15

};

35 'eodif

Contents of FinalExam . cpp

5

•7

Yo

3

4

*include" rinalExam. h"

11-···_····_···*·············_*_·······_··_*·_-**-_··* **-*

*

II set function

/1 The parameters are the number of questions and the

8

void FinalExam :: set(int questions, iot missed) { double numericScore; 1/ To hold the numeric score

Ri

9 10 11 12 13 14

/1 Set the number of questions and number missed. numQuestions = questions; numMissed = missed;

,.

an

15

II Calculate the points for each question. pointsEach = 100 . 0 I numQuestions i

20 21 22 2]

II Calculate the numeric score for this exam . numeriCScore = 100.0 - (missed * pointsEach);

Ha

ss

17 18 19

II Call the i n herited setScore function to eet II the numeric score.

24

setScore(numericScore);

25

26

*

/1 number of questi.ons missed . • //*** ** ******* ••• ***** •••••• ******* ••• **************** **k_

az

1 2

)

ad

The only new notation in this code is in line 5 of the FinalExam.h file, which reads cla ss FinalExam : public GradedActivity

uh a

m

m

This line indicates rhe name of the class being decla red and the na me of the base class it is derived from. Finall'':xam is the name of the class being declared and GradedActivity is the name of the base class it inherits from. class Fi na l Exam

t

Class being declared (t he derived class)

public

Base class

IE we want to express the relationship between t he twO classes, we can say tha t a PinalExam is a GradedActivity.

M

900

The word public, which precedes the name of the base class in Ime 5 of the FinalExam . h file, is the base class access specification . It affects how the members of the base class arc in herited by the derived class. When you create an object of a derived class, you can think

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 901

15.1 What Is Inheritance?

us uf

i

of it as being built on top of an object of the base class . The members of the base class object become members of the derived class object. How the base class members appear in the derived class is determined by the base class access specification.

az

Yo

Although we will discuss this topic in more derail in (he next sect ion, let's see how it works in this example. T he GradedActivity class has both private members and public members. The FinalExam class is derived from the GradedActivi ty class, using public access specifica tion . This means that the publ ic members of the GradedActivity class will become public members of the Fi nalExam class. The private members of the GradedActivity class cannot be accessed directly by code in the Fi nalExam class. Although the private members of the GradedActivity class are inhc l路ited, it's as though they arc invisible CO the code in the FinalExam class. T hey can only be accessed by the member func tions o f the GradedActivity class. Here is a list of the members of the FinalExam class:

Ri

Private Members: int numQuestions double pointsEach int numMissed

Defined in the FinalExam class Defined in the FinalExam class Defined in the FinalExam class Defined in the Fi nalExam class Defined in the FinalExam class Defi ned in the FinalExam class Inherited fro m GradedActivity Inherited from Gr adedActivity Inherited from Gr adedActivity

ad

Ha

FinalExam( ) FinalExam(i nt , intI set(int, int) getNumQuestions() getPoint6Each( ) getNumMissed( ) setScore(double) getscore( ) getLetterGrade ( )

ss

Public Members:

an

Declared in rhe FinalExam class Declared in the FinalExam class Declared in the FinalExam class

m

m

T he GradedActivity class has one private member, the variable score. Notice thar it is not listed as a member of the FinalExam class . It is still inherited by the derived class, but because it is a private membe r of the base class, only member functions of the base cl ass may access it. It is truly private to the base class. Because the func tions setScore, getScore, and getLet terGrade are public members of the base class, (hey also become public members of rhe denved class.

M

uh a

You will also notice that the GradedActivity class constructors are not listed among the members of the FinalExam class. Although the base class constructors still exist, it makes se nse that they are not members of the derived class because the ir purpose is to construct objects of the base class. In the next section we discuss in more detail how base cl ass conStrUCtors operate.

Let's take a closer look at the fi nalExam class constructors. The defau lt constr uctor appears in lines 13 through 16 of the Fi nalE xam. h file. It simply assigns 0 to each of the class's member variables_ Another conStr uctor appears in lines 19 through 20. Th is constructor accepts two arguments, one fo r the number of questions on the exam, and one for the number of questions missed. T his constructo r merely passes those va lues as argumems to the set function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 90 2

Chapter 15

Inheritance. Polymorphism, and Virtual Functions

us uf

i

The set function is defined in FinalExam . cpp. It accepts two arguments: the number of questions on the exam, and the number of questions missed by the student. In lines 14 and 15 these values are assigned to the numQuestions and numHissed member variables. 1n line 18 the number of points for each question is calculated. In line 21 the numeric test score is calculated. In line 25, the last statement in the funct ion reads:

Yo

setScore(numericScore);

T his is a call to rhe setScore function. Al though no setScore funct ion appears In the FinalExam class, it is inherited from the GradedActivity class. Program 15-2 demonstrates the FinalExam class.

3 4 5

II This program demonstrates a base class and a derived class.

t i nc l ude <iostream> tinclude <iomanip> ti nclude "FinalExam . h" using namespace std;

Ri

1 2

az

Program 15-2

6

B 9

10

int main{) ( int questions; II Number of questions on the exam II Number of questions missed by the student i nt missedj

an

7

11 12

15 16 17 18

II Get the number of questions the student missed. cout « "How many questions did the student miss? " ; cin » missed;

19 20 21 22

1/ Define a FinalExam object and initialize it with 1/ the values entered. FinalExam test(guestions, missed ) ;

ss

14

/1 Get the number of questions on the final exam . cout « "How many questions are on the final exam? "; cin » que stions;

ad

Ha

13

23

II Display the test results .

2.

cout « cout «

27

«

26

cout «

"The exam score i s

29

cout «

"The exam grade 15

test.getPointsEach()

« test.getScore( ) « endl ; " « test.getLetterGrade() «

end1;

return 0;

uh a

32

setprecision (2); "\nEach question counts " « " points . \n";

m

30

31

m

24 25

}

Program Output with Example Input Shown In Bold HOw many ques t ions are on the final exam? 20 [Enter]

M

How many que stions did the student miss? 3 (Enter]

Each question counts 5 points.

The e x am score is B5

The exam grade is B

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 903

i

15.1 What Is Inheritance?

cout « cout «

"The exam score is " « "The exam grade is " «

us uf

Notice in Jines 28 and 29 that (he public member func tions of the GradedActivity class may be directly called by the test object: test . getScore() « endl; test.getLetterGrade() « endl ;

Yo

The getScore and getLetterGrade member functions are inherited as public members of the FinalExam class, so they may be accessed like any other public member.

Inheritance does nOt work in reverse. It is n Ot possible fol' a base class t o ca ll a member function of a derived class. For exa mple, the following classes will not compile !n a program beca use the BadBase constructor attempts to ca ll a function in its derived class: class BadBase

,

class Derived

public BadBase

Ri

)

private : int Xi public : BadBaSe() { x - getVal(); }

az

{

II Error !

{

an

private :

ss

int y; public: Derived(int z) { y = z ; ) int getVa l () { return y ; }

~ Checkpoint

Ha

} ;

15.2 15.3

ad

Here is the fi rst line of a class declarat ion. Circle the name of the base class: class Truck : public vehicle Circle the name of the derived class in rhe following declara tion line: class Truck : public Vehicle Suppose a program has the following class declarations:

15.1

class Shape

m

{

M

uh a

m

private: double area; public ~ void setArea(double a) { area = a; } doub le getArea() { return area; }

};

class Circle

public Shape

{

private : double radius ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

Inheritance, Polymorphism, and Virtual Functions

= r;

*

setArea(3 . 14

*

r

r) ;

us uf

{ radius

i

public: void setRadius{double r) }

double getRadius() { return radius; }

Answer the following questions concern ing these classes:

Yo

) ;

A) When an object of (he Circle class is created, what are its private members?

az

B) When an object of the Circle class is created , what are its public members? C} What members of the shape class are nor accessible to member functions of the Circle cl ass?

Ri

Protected Members and Class Access

co NC EPT: Protected members o f a ba se cla ss a re like private members, but th ey may be accessed by derived classes . The base class access specification

an

determines how private, public, aod protected base class members are accessed when they are inherited by the derived classes .

Ha

ss

Until now you have used twO access spec ifications within a class: private and public. C++ provides a third access specification, protected. Protected members of a base class are like private members, except they may be accessed by funct ions in a derived class. To the rest of the program, however, protected members are inaccess ible .

The following code shows a modified version of the GradedActivity class declaration. T he private member of the class has been made protecTed. This file is stored in the Student Source Code Folder Chapter 1S\GradedActivity version 2. The implementation file,

ad

GradedActivity . cpp has not changed, so it is not shown again in this example.

1

2

jifndef GRADEDACTIVITY H

.defi ne GRADEDACTIVITY H

m

3

m

Contents of GradedActivity . h (Version 2)

4

II GradedActivity class declaration

class GradedActivity {

uh a

5 6

7 8

9 10

M

904

protected: double score;

II To hold the numeric score

public:

11

II Default constructor

l?

GradedActivity() { score '" 0.0; }

13 14

15

1/ Constructor

16

GradedAct ivity(double s)

,.

17

{ score = s j

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15.2 Protected Members and Class Access

22 23

i us uf

II Mutator function void setScore(double s) { score '" s; }

19

20 21

II Accessor functions double getScore() const { return score; }

24 25

Yo

2. 27

ch3r getLetterGrade(} const;

28

};

29

'endif

905

Ri

az

Now we wilJ look at a modified version of the FinalExam class, which is derived from tllis version of the GradedActivity class. This version of the FinalExam class has a new member fu nction named adjustScore. This func tion directly accesses the GradedActivity class's score member variable. If the coneent of the score variable has a fractional part of O.S or greater, the function rounds score up to the next whole number. The set function calls rhe adjustScore function after it calculates the numeric score. (These files arc stol'ed in the Student Source Code Folder Chapter 15 \Gr adedActivi ty Version 2.)

an

Contents of FinalExam. h (Version 2) 'ifndef fINALEXAM H 'define FINALEXAM H hnclude "GradedActivity.h路路

5

class Fina1Exam : public GradedActivity

.

12

m

13 14 15 16

(

private: lnt numQuestions; II Number of questions double pointsEach; II Points for each question lnt numMissed ; II Number of questions missed public : II Default constructor FlnalBxam() { numQuestions = 0; pointsEach = 0 . 0; numMissed = 0; }

Ha

7 8 9 10 l1

ad

,

ss

1 2 3

17

m

18 19 20

II Constructor FinalExam(int questions, int missed) { set (questions, missed); }

21

uh a

22 23

"

25 26 28

II Accessor functions double getNumQuestions() const { return numQuestions ; }

30 31

double get PointsEach() const { return pointsEach, }

27

M

II Mutator functions void set(int, intI; I I Defined in finalE xam. cpp void adjustScore(); II Defined in FinalExam.cpp

2'

32

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Inheritance, Polymorphism, and Virtual Functions

{ return numMissedi

34

35 36

i

int getNUmMi ssed() canst

33

}

us uf

Chapter 15

}; jendif

Conte nts of FinalExam . cpp (Ve rsion 2) *include "FlnalExam.h"

Yo

1 2 3 4

11*···*·**-_··_---------------*-------_·_------------***** /1 set function

5 6

II The parameters are the number of questions and the II number of questions mi ssed .

7 8

11------------_·_--*---_·_····_-------_····_---------- ****

9

void FinaIExam: : set(int questions, int missed)

numMissed

1/ Calculate the points for each question . pointsEach = 100.0 I nurnQuestions;

"

20

II Calculate the numeric score for th i s exam. numericS core = 100.0 - (missed * po i ntsEach);

21 22

Call the inherited setScore function to set the numeric score. setScore(numericScore)i

24

25

2,

II II

28 29 )

11**************************************************** **********

m

34

ad

Call the adjustScore function to adjust the score . adjustScore();

27

II II

Definition of Test : :adjustScore . If score is within 0 . 5 points of the next whole point, it r ounds the score up I I and recalculates the letter grade.

m

35

Ha

II II

23

32

Ri

= missed ;

an

"

17 18

33

II To hold the numeric score

/1 Set the number of questions and number missed. numQuest i ons = questions:

13

14 15

30 31

az

{

double numericScorei

* *

ss

10 11 12

* * *

11**************************************************** ** * *******

38

void FinaIExam : :ad j ustScore()

39

{

uh a

36 37

40

double fraction - score - static_ca st<int>(score);

41

M

906

42

if (fraction

43

{

47

0.5)

II Adjust the score variable in the GradedActivity class . score +~ (1.0 - fraction);

44 45 46

>~

) )

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 90 7

, 5.2 Protected Members and Class Access

us uf

i

Program ]5-3 demonstrares these versions of rhe GradedActivity and FinalExam classes. (This file is also sto red in the Student Source Code Folder Chapter 15 \ GradedActivity Version 2. )

Program 15-3 // This program demonstrates a base class with a

// protected member . ' i nclude <iostream> 'i nclude <iomanip> ti nclude "FinalExam . h" using names pace std;

5 6 7 8 9 10

int main ()

az

3 4

Yo

1

2

int questions; /1 Number of questions on the exam int missed; // Number of questions missed by the student

Ri

11 12 13 14

1/ Get the number o f questions on the final exam. cout « "How many questions are on the fina l exam? ": cin » questions;

15

"

II Get the number of questions the student missed . cout « "How many questions did the student miss? "; cin » missed;

an

17

18

ss

19 20

II Define a FinalExam object a nd initialize it with II the values entered.

23

FinalExam test(questions, missed):

Ha

21 22 24

// Display the adjusted test result s . cout « setprecision(2) « fixed; cout « "\nEach question counts " « test.getpointsEach() « " points. \ n"; cout « "The adjusted exam score is " « test. getScore ( ) « endl; cout « "The exam grade is " « test.getLetterGrade() « endl;

25

2'

27 28

m

return 0; )

m

35

ad

29 30 31 32 33 34

Program Output with Example Input Shown In Bold

uh a

How many questions are on the final exam? 16 [Enter] How many questions did the student miss? 5 [Enter]

M

Each question counts 6 . 25 points . The adjusted exam score is 69.00 The e xam grade is 0 The program works as planned. In the example run) the student missed five questions, which are worth 6.25 points each. The unadjusted score would be 68.75. The score was adjusted to 69.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

Inheritance, Polymorphism, and Virtual Functions

us uf

i

More About Base Class Access Specification The first line of the FinalExam class declaration reads: class FinalExam ; public GradedActi vity

Yo

This declaration gives public access specification to the base class. Recall from Ollr earlier discussion char base class access specification affects how inhe rited base class members are accessed . Be careful nOt to confuse base class access specification with member access speci fi ca tion. Membe r access specification determines how members that are defined within the class are accessed. Base class access speci fication determines how inherited members are accessed.

Table

Ri

az

When you create an object o f a derived class, it loherits the members of the base d ass. The derived class can have its own private, protected, and public members, bur what is the access specification of the inherjred members? T his is dete rmined by the base class access specification. Table 15-1 summarizes how base class access specifica tion affects the way that base class members are inherited. 15~1

How Members of the Base Class Appear 10 the Derived Class

private

Private members of the base class are inaccessible to the derived class .

an

Base Class Access Specification

ss

Protected members of the base class become pri vate members of the derived class. Public members of the base cll'lsS become private members of the deriveJ cla ss. Private membe rs of me base class a re jna~cessible to the derived class. Protected members of the base class become protected members of the derived class.

Ha

protected

ad

Public members of the base class become protected members of the derived cla ss . public

Pri vate members of the base class are inaccessible to the derived class.

m

Protected mem bers of the base class become protected members of the derived class. Public members of the base class become public members of the denved class .

uh a

m

As you can see from Table 1 5 ~ 1, class access specifica tion gives you a great dea l of flexibil ity in determining how base class members will appear in the derived class . Think of a base class's access specifica tion as a filter that base class members must pass through when becoming inheri ted members of a derived class. Th is is illustrated In Figure 15-3. NOTE: If the base class access specification is left Out of a declaration, the default access specification is private. For examp le, in the following declaration, Grade is declared as a private base class:

M

908

class Test : Grade

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH , 5.2 Protected Member.s and Class Access

How base class members appear in the derived class

Base class members

private y

x is inaccessible.

base class

- - - - -- -- -.. ,

public: z

protected

x is inaccessible.

base class

public : z

private : x protected: y

- - -- - - - - -.... protected : y protected : z public base class

public: z

an

~ Checkpoint

az

y

Ri

private: x protected :

private: y private: "Z

Yo

private: x protected:

us uf

i

Figure 15-3

909

What is the difference between private members and protected members?

15.5

What is the difference between member access specification and class access specification?

15.6

Suppose a program has the following class declaration:

Ha

ss

15.4

II Declaration of CheckPoint class. class CheckPoint {

m

ad

private: int ai protected: int bi int c; void setA( int xl { a public: void setB(int yl { b void setC(int , I { c

= x; }

Yi } =

z; }

M

uh a

m

I,

Answer the following questions regarding the class: A) Suppose another class, QUiz, is derived fr om the CheckPoint class. H ere is the first line of its declaration: class Quiz : private CheckPoint Indica te whether each member of the CheckPoint class is private, protected, public, or inaccessible: a b

c setA setS sete

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

inheritance, Polymorphism, and Virtual Functions

B) Suppose the Quiz class, derived from the CheckPo i nt class, is declared as

us uf

class Quiz : protected Checkpoint

i

910

Indicate whether each member of the CheckPoint class is private, protected, public, or inaccessib le: a b

c

setA

Yo

setB setC

C) Suppose the Quiz class, derived from the CheckPoint class, is declared as class Quiz : public Che ckpoint Indicate whether each member of the CheckPoint class is private,

inaccess ible:

az

protected, public, or

a b

Ri

c setA setS setC

D) Suppose the Quiz class, derived from the CheckPoint class, is declared as

an

class Quiz : Checkpoint

Is the CheckPoint class a private, public, or protected base class?

Ha

ss

Constructors and Destructors in Base and Derived Classes CONCEPT: Th e base class's constructOr is call ed before the deri ved class's

ad

constructor. The destru ctors a re ca lled in reverse order, with the deri ved cl ass's destructor being call ed first.

m

m

In in heritance, the base class constructOr is called before the derived class constructor. Destructors a re called in reverse order. Program 15-4 shows a simple set of demonstration classes, each with a default constructor and a destructor. T he DerivedClass class is derived from the BaseClass class. Messages are displayed by the constructOrs and destructo rs to demonstrate when each is called.

Program 15-4

3 4

¥include <iost r eam>

usi ng namespace std;

11 ** ** *********** *** **** *********·

II BaseClass declaration

M

5 6 7

II Th i s program demonst r ates the order in which base and /1 derived class constructors and destructors are called .

uh a

1 2

B

11 *·· · ·· · ····*·*·**····****···****

9

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15.3 Constructors and Destructors in Base and Derived Classes

i

class BaseClass

11

12 13

14

public : BaseClass ( ) { cout «

II Constructor

"This is the BaseClass constructor.\n"; }

15

16 };

20

//****** ***** *** ******** ********* * // DerivedClass declaration * //**** ********************* *******

21 22

az

18 19

Yo

-BaseClass() /1 Destr uctor { cout« "This is the BaseC las s destructor.\n"; }

17

23 cl a ss DerivedClass : public BaseClass {

pUblic : DerivedClass() // constructor { cout « "This is the DerivedClass constructor . \ n " ; }

Ri

24 25 26 27 28

29

34

-De rivedClass{) // Destructor { cout« "This is the Deri vedClass destructor.\n"; )

an

30 31 32 33

};

/1 mai n functi on • // ****** ** ****** ******************

37 38

int main()

39

{

Ha

cout «

40

ss

36

35

"We will now define a De rivedClass object . \n" ;

41

DerivedClass object ;

42 43 44

ad

cout « "The program is now going to end . \n "; return 0 ; )

m

45 46

us uf

10

9 11

uh a

m

Program Output We will now define a OerivedClass object . This is the BaseClass constructor. This is the DerivedClass constructor. The pro gram is now going to end. This is the DerivedClass destructor . This is the BaseClass destructor.

M

Passing Arguments to Base Class Constructors

In Program 15-4, both the base dass and derived class have default constructors, that are called automatically. But what if the base class's conStructor takes argu ments? What if there is more than one constructor in the base class? The answer to these questions is to let {he derived class constructor pass arguments ro the base class constructor. For example, consider rhe followi ng class:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

Inheritance, Polymorphism, and Virtual Functions

us uf

1 2

i

Contents of Rectangle. h 'ifndef RECTANGLE H 'def i ne RECTANGLE tl

4 5

class Rectangle {

6 7 8 9

private : doubl e width; double length; public: /1 Default constructor

11

Rectangle()

{ width - 0 . 0;

13 14 15 16 17

length: 0 . 0; } /1 Constructor ' 2 Rec t angle(double w, double len) { width: Wi length = len; }

18 19

double getWidth() canst { return width; }

22 23

double gâ&#x201A;ŹtLeng t h () comIc

an

20 21

{ return length ; }

ss

24 25 26 27

double getArea() canst { return width * length: } }i lend i f

Ha

28 29

az

12

Ri

10

Yo

3

ad

This class is designed to hold da ta about a rt:l.:tangie. It specifics twO constructors. The default constructor, in lines 11 through 13, simply initializes the width and l e ngth member variables to 0.0. The second constructor, in lines 16 through 18, takes twO arguments, which arc assigned to the width and length membe r variables. Now let's look at a cl ass that is der ived from the Rectangle class:

l ifndef CUBE H 'define CUBE_ H !include "Rectangle.h"

m

1 2 3

m

Contents of Cube. h

4

class Cube : public Rectangle { protected : doubl e height; double volume; public : II Default constructor Cube() : Rectangle() { height ~ O.Oi volume = 0 . 0 ; }

uh a

5

6

7 8 9

M

912

10 11 12

13 14

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15.3 Constructors and Destructors in Base and Derived Classes

17 18 19 20

21

double getHeight() const { return height; }

22 23 24

double getVolume() const { return volume; }

25

};

26

'endif

i Rectangle(w, len)

Yo

II Constructor #2 Cube (double w, double len, double h) ( height h; volume = getArea() * hi }

15

us uf

I.

913

az

The Cube class is designed to hold data about cubes, which not only have a length and width, but a height and volume as well. Look at line 12, which is the first line of the Cube class's default constructor:

Ri

Cube{) : Rectangle{)

an

Notice the added notatio n in the header of the constructor. A colon is placed after the derived class constructor's parentheses, followed by a function call to a base class constructor. In this case, the base class's default constructOr is being called. When this Cube class constructOr executes, it will first call the Rectangle class's defaul t constructOr. This is illustrated here:

I

Rectangle( )

\

Ha

Derived Class Constructor

ss

Cube( )

Call to the Base Class Constructor

The general format of this type of constructor declaration is : BaseClasSNarne(ArgumentList}

ad

ClassName::ClasSName(ParameterList)

m

You can also pass arguments to the base class conStruCtOr, as shown in the Cube class's second constructor. Look at line 16: Cube{double w, double len , double h) : Rectangle(w, len)

m

This Cube class constructor has three parameters: IN, len, and h. Notice thac che Rectangle class's constructor is called, and the wand len parameters arc passed as arguments. This causes the Rectangle class's second constructor to be called.

M

uh a

You only write this notation in the definit ion of a constructor, not in a prototype. In this examp le, the derived class constructOr is written in line (inside the class declaration), so the notation [hat coma ins the call to the base class conStructOr appears there. If the constructor were defined outside the class, the notation would appear in the function header. For example, the Cube class could appear as follows.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

914

Inheritance, Polymorphism, and Virtual Functions

public Rectangle

class Cube

i

{

us uf

protected: double height; double volume; public:

/1 Default constructor Cube( )

: Rectangle()

{ height

~

0 . 0; volume - 0 . 0 ; }

Yo

II Const r uc t or 12 Cube{double , double, double);

double getHeight() const { return height; }

az

double getVolume() const

{ return volume; } ) ;

Ri

/1 Cube class constructor 12 Cube : :Cube(double w, double len, double h) {

h;

volume

getArea() ." h;

an

height

Rectang l e(w, len)

T he base class constructor is always executed before the derived class constructor. When the Rectangle COnStrUCtor finishes~ the Cube constructor is rhen executed.

Derived cia!';!'; conStructor paramerers Literal values Global variables that a re accessible to the file containing the derived class constructor definition Expressions involving any of these items

ad

• • •

Ha

ss

Any !lleral value or variable that is in scope may be used as an argument to the derived class constructor. Usually, one or more of the arguments passed to the derived class constructor are, in turn, passed to the base class constructor. The values that may be used as base class constructor arguments a re

Program 15-5 shows the Rectan91e a nd Cube classes in use.

3 4

5

II class constructor. 'include <iostream> linclude "Cube.h " using names pace std ;

M

uh a

6

II This pro9ram demonstrates passing arguments to a base

m

1 2

m

Program 15-5

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15.3 Constructors and Destructors in Base and Derived Classes

9

10 11

i

int main() { double cubeWi dth; double cubeLength; double cubeHeight;

II II II

us uf

7 8

To hold the cube's wi dth To hol d the cube's length To hol d the cube's height

Get the cout « cout « cin » cout « cin » cout « cin »

17 18

19 20 21 22 23

the width , length, and height of cube from the user. "Enter the dimensions of a cube:\n"; "Width: "; cubeWidth; "Length: "; cubeLength; "Height: "; cubeHeight;

II II

az

II II

14 15 16

Yo

12

13

9lS

25

Ri

Define a Cube object a n d use the dimensions entered by the user. Cube myCube(cubeWidth, cubeLength, cubeHeight);

24 26

II Display the Cube object's properties . cout « "Here are the cube's properties:\n"; cout « "width: " « myCube . getWidth() « endl; cout « "Length : " « myCube . getLength() « endl; cout « "Height: " « mycube.getHeight() « endl; cout « "Base area: " « myCube . getArea() « endl; cout « "Volume: " « myCube.getVolume() « endl;

ss

an

27 28 29 30 31 32 33

3' return 0;

35 36

Ha

}

Program Output with Example Input Shown In Bold

m

m

ad

Enter the dimensions of a cube: width: 10 [Enter] Length: 15 [Enter] Height: 12 [Enter] Here are the cube's properties: width: 10 Length: 15 Height: 12 Base area: 150 Volume: 1800

M

uh a

NOTE: If the base class has no default conStructOr, then the derived class must have a ( ) "-_c_o_n_'_t_,,_,_c _to_,__t h__a_r _c_a_II_, _o_n__, _o_f_t_h_'__b_a_s_,_c_l_"_, ,__c_o_n_'_r_ru_c_t_o_'_s_. ______________________________-"

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

Checkpoint 15 .7

i

~

Inheritance, Polymorphism, and Virtual Functions

us uf

916

What will the following program displa y? 'include <iostream>

using namespace std; class Sky

Yo

{

pUb l ic: Sky( )

{ cout«

"Entering the sky.\n"; }

-Sky( )

{ cout «

"Leaving the sky.\n"; }

class Ground

az

} ;

public Sky

{

public:

{ cout «

Ri

Ground( )

"Entering the Ground. \0"; }

- Grounrl( )

{ cout «

"Leaving the Ground. \n" ; }

an

};

int main( ) {

Ground object;

ss

return O·, }

What will the following program displa y?

Ha

15.8

'include <iostream>

using namespace std;

class Sky {

ad

public :

Sky( )

m

{ cout « "Enter i ng the sky . \n" ; } Sky(char *color) { cout « "The sky is " « color «

endl; }

-Sky( )

{ cout «

"Leaving the sky . \n" ; }

m

} ;

M

uh a

class Gr ound

public Sky

public : Grounrl( ) { cout« "Entering the Ground . \n"; } Ground(char *cl, char *c2) : Sky{cl) { cout « ""The ground i s "" « c2 « endl; -Ground ( ) { cout« "Leav i ng the Ground . \n"; } };

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15.4 Redefining Base Class Func.tions

us uf

i

int main( )

917

{

Redefining Base Class Functions

Yo

Ground object i return O路,

CONCEPT; A b ~s e class member function may be redefined in

<l

derived class .

RedcfUlilLg a

Hase Clas~

class GradedAct i vity (

protected: char letter: II To hold the letter gr ade double score; II To hold the numeric score void det ermineGradc()i II Determi nes the letter grade pUblic : II Default constructor GradedActivity( ) { letter = . ' : score = 0 . 0 ; }

ss

an

FunClion in a Dn ivtd Class

Ri

az

lnheritance is commonly used to extend a cbss or give it aJJil iunal capabilities . Some路 ti mes it m~y be helpful to overload a base class function with a function of tht sa lilt Ilame in the derived class. For example, recall the GradedActi vity class tha r w~s presented ear路 lier in this chapter:

Ha

II Mutator f unction void setScore(double 5) { score '" s ; determineGrade():}

ad

II Accessor functions double getScore() const { return score ;

)

m

char getLetterGrade() const { return letter; }

uh a

m

T his class holds a nume ric score and determ ines a letter grade based on tha t score. T he setScore member function StOres a va lue in score, then calls the determineGrade member function to determine the letter grade.

M

Suppose a teacher wants to "curve" a numeric score before the lener grade is determ ined. For example, Dr. Harr ison derermines thar in order to curve the grades in her class she must multiply each student's score by a cen ain percentage. T his gives an adjusted score, which is used ro dete rmine the letter grade. T he following curvedActivHy class is de rived from the GradedActivity class. it mul路 tip lies the numeric score by a pen.:entage, and passes [hat value as an a rgu ment to the base class's s e tScore funcrion. (Th is file is stored in the Stud em SOlJ(ce Code Folder Chapter lS\CurvedActivity.)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

918

Inheritance, Polymorphism, and Virtual Functions

#ifnde f CURVEDACTIVITY_H #define CURVEDACTIVITY_H #include "GradedActivity . h"

4

6

(

7

prot~cted :

8 9

II Una d justed score I I Curve percentage

pUblic : 1/ Def ault constructor CurvedActivity{): GradedActivity() { rawS core '" 0.0; percentage'" 0.0; }

14 15 16

/1 Mutator functions void setScore(double s)

,.

{ rawS core '" s ;

l7

az

10 11 12 13

double rawScore; double percentage;

Yo

class CurvedActivity : public GradedActivity

Ri

5

us uf

1 2 3

i

Contents of CurvedActivity. h

GradedActivity : :setScore(rawScore * percentage); }

19 20

void setPercentage(double C) { percentage '" c; }

an

21 22 23

II Accessor functions double getPercentage() canst { return percentage; }

24

ss

2S

2. };

30

#endif

Ha

double getRawScore(l canst { return rawScore; }

27 2S 29

T his CurvedActivity class has the following member variables; rawScore

This variable holds the swdem's unadjusted score.

percentage

This variable holds the value that the unadjusted score must be multipli ed by to get the curved score.

ad

m

It also has the following member functions:

A default constructor that calls the GradedActi vity default constructor. then sets rawScore and percentage to 0.0. setScore T his funct ion accepts an argument that is the stu dent's unadjusted score . The func tion stores the argument in the

m

M

uh a

()

• • •

rawScore variable, then passes rawScore * percentage

set Percentage get Pe rcentage getRawScore

as an argument to the base class's setScore function. This function Storts a value in the percentage variab le. This fUllction returns the value in the percentage va riable. This function rerurns the value in the rawScore variable.

NOTE: Although we are not using the CurvedActivity class as a base class, it still has a protected member section. This is because we might want to use the CurvedActivity class itself as a base class, a.<; yOll will see in the next section.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

15.4 Redefining Base Class Functions

i

919

us uf

Notice that the curvedActivity class has a setScore member fu nction. This function has the same name as one of (he base class member functions. When a derived class's member function has the same name as a base class member function, it is said that the derived cl ass function redefines the base class function. When an objecr of the derived class calls the function, it calls the derived class's version of the function.

az

Yo

There is a distinction betwee n redefining a function and overloading a function. An overloaded function is one with the same name as o ne or more other functions, but with a diffe rent parameter list. T he com piler uses the arguments passed [Q rhe functio n to tell which version to call. Overloading can rake place WIth regular functions rhat are not members of a class. Overloading can also take place inside a class when two or more member functio ns of the same class have the same name. T hese member functions must have differen t parameter lists for the comp iler to tell them apart in fu nction calls .

Ri

Redefining ha p pens when a denved cl ass has a function with the same name as a base class function. T he parameter lists of the two fu nctions can be the same because the derived class function is always called by objects of the derived class ty pe. Let's continue our look a t the cllrvedActivity class. Here is the setScore member funct ion:

an

void setScOre(dOllble s) { rawScore = Si GradedActivity : :setScore(rawScore * percentage) ; }

Ha

ss

This functio n accepts an argument that should be the student's unadj usted numeric score, into the pa rameter s. This value is stored in the rawScore variable. T hen the following statement is exec uted: GradedActivity :: setScor e( r awScore * percentage) ; This statement calls the base class's version of the setS core func tion with the expression

rawScore * percentage passed as an argumem. Notice that the name of the base class

ad

and the scope resolution operator precede the name of the funC Tion. Th is specifies that the base class's ve rsion of rhe setScore fu nction is being cal led. A derived class function may call a base class function of [he same name lLsing this notation, which takes this form :

m

BaseClassName: :functionName(ArgumentList);

m

Program 15-6 shows the GradedActivity and CurvedActivity classes used in a complete program. (This file is stored in the Student Source Code Folder Chapter 15\ Cur vedActivity.)

uh a

Program 15-6

1

1/ This program demonstrates a class t hat redefines

2

II

,

a base class tunction . <iostream~

jinclude

<iomanip~

5

iinclude "Curved1\ctivit y . h"

M

iinclude

4

6 7

using namespace std; (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

Inheritance, Polymorphism, and Virtual Functions

Program 15-6 int main() {

10

double numericScore;

/1 To hold the numeric score

11 12

double percentage;

1/ To hold curve percentage

13 14 15

/1 Define a curvedActivity object. Cur vedAct ivity exam;

16 17

1/ Get the unadjusted score. cout « "Enter the student's raw numeric score : "i

18

cin »

numericScore;

az

I.

us uf

8 9

i

(continued)

Yo

920

/1 Get the curve percentage.

cout « "Enter the curve percentage for th is s tudent : "; cin » percentage;

24

II Send the values to t he exam object. exam.setPercentage(percentage);

25

exam.setScore(numericScore);

28

II Display the grade data. cout « fixed « setprecision(2): cout « "The raw score is "

31 32 33 34

« cout «

35

«

«

exam . getScore ( ) «

cout «

3.

"The

endl ;

curved grade is "

exam . getLetterGrade() «

return 0;

37

38

exam . getRawScore() « endl; "The curved score is "

ss

30

Ha

2.

an

26 27

Ri

20 21 22 23

)

endl;

ad

Program Output with Example Input Shown In Bold Enter the student's raw numeric score: 87 [Enter]

Enter the curve percentage for this student: 1.06 [Enter]

m

The raw score i s 87.00

The curved score is 92 . 22

m

The curved grade is A

uh a

It is important to nOte that even though a derived class may redefine a fun ction in the base class, objects that are defined of the base class type still call (he base dass ve rsion of the function. This is demonstrated in Program 15 ~ 7 .

Program 15-7 1

M

2

3

4 5

II Th is program demonstrates that when a derived class function II overrides a base class function, objects of the base class

/1 still call the base class version of the function. #include <iostream> using names pace std;

6

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 921

11

12 13 14 15

us uf

9 10

class BaseClass { public : void showMessage() { cout ÂŤ "This is the Base class . \n"; } };

c las s DerivedClass

pub l ic BaseClaGG

{

19

);

az

18

public : void showMessage() cout ÂŤ "This is the Derived class . \n"; }

16 17

20

21

int main()

22

24

25 26

an

b.s howMessage(); d,showMessage() ;

27 28

retur n 0 ;

29 30

Ri

BaseClass b; DerivedClass d;

23

Yo

7 8

i

15.5 Class Hierarchies

}

ss

Program Output

Ha

This is the Base class, This is the Derived class,

m

ad

In Program 15-7, a class named BaseClass is declared with a member funct ion named showMessage. A class na med DerivedCl a ss is then declared, also with a showMessage member funct ion. As their names imply, DerivedCICliSS is derived from BaseClass. Two objects, band d, are defined in function main. The object b is a BaseClass object and d is a DerivedClass object. When b is used to ca ll the showMessage fun ction, it is the BaseC l ass version that is executed. Li kewise, when d is used to ca ll showMessage, the DerivedClass version is used .

m

Class Hierarchies

uh a

CONCEPT: A base class can also be derived from another cla ss .

M

Sometimes it is desirable to esrablish a hierarchy of classes in which one class inherits from a second class, which in turn inherits from a rhird class, as illustrated by Figure 15-4. In some cases, the inheritance of classes goes on for many layers.

In Figure 15-4, classC inherits ClassB's members, including the ones that ClassB inherhell fru m Cld::HIA. Le ( 'S louk (It (Ill eXi:l llI p1c of such i:I cha in of iniH:rirallcc. Conside r the following PassFailActiv ity class, which inherits from the GradedActivity class. T he

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 922

cnaprer 15

Inllenrance. POlymorphIsm, and Virtual Functjons

us uf

i

Figure 15-4

Yo

ClassA

an

Classe

Ri

'f I

az

ClassB

class is intended to derermine a lener grade of 'pofoc passing) or 'F' for failing. (This file is

ss

stored in (he Student Source Cod e Folder Chapter l S \ PassFailActivity. )

Contents of PassFailActivity. h 'ifndef PASSFAILACTIVITY H 'define PASSFAILACTIVITY H Hnclude "GradedActivity . h"

Ha

1 2 3

4

class PassFailActivity : pub lic GradedActivity

6

(

7

protected :

• 9

double minpassingScore ; /1 Mi n imum passing score . public : 1/ Default constructor PassFailActivity() : GradedAct i vity()

m

10 11

ad

5

12

uh am

!3 14 15 16

{ minPassi ngscore - 0 . 0; }

II Constructor PassFailActivity(double mps) : GradedActivity() { minpassingScore = mps ; }

17

18 19 20

II Mutator void setMi nPa ssingScore(double nps) { minpassingScore = mps ; }

M

21 22 23 24

I I Accessors double getMinPassingScore() const { return minpas singScore ; }

25 char getLetterGrade() const ;

26 27

};

28

fendif

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

923

i

15.5 Class Hierarchies

Yo

us uf

The PassFailActivity class has a private member variable named minPassingScore. This variable holds the minimum passing score for an activity. The default constructor, in lines 11 through 12, sets minpassingScore to 0.0. An overloaded constructor in lines 15 through 16 accepts a double argument that is the minimum passing grade for the activity. This value is stored in the minPassingScore variable. The getLetterGrade member function is defined 10 the following PassFailActivi ty . cpp file. (This file is also stored in the Student Source Code Folder Chapter 1S\PassFailActivity.)

Contents of PassFailActivity. cpp 1

tinclude "PassFailActivity . h"

2

6 7

az

5

•• **** ** II Member function PassFailActivity: : getLetterGrade • II This function returns 'P' if the score is passing, • /1 otherwise it returns 'F' . • /1****····*··*·*········· · ··········· •• ··.** •••••••••• ••

II~~*~*~***~**~*~*******~***********************

Ri

3

4

e

char passFailActivity : :getLetterGrarle() const {

11

char letterGradei

12 13

if (score > - minpassingScore) letterGrade = 'P'; else letterGrade - 'F';

14

ss

15 16

17

return letterGrade;

Ha

18 19

an

9 10

}

ad

This getLetterGrade member func rion redefines the getLetterGrade member funcrion of GradedActivity class. This version of the function rerurns a grade of 'P' if the nume ric score IS greater than o r equal to minPassingScore. Otherwise, the function returns a grade of ' F' .

uh a

m

m

The passfailActivity class represents the general characteristics of a student's pass-orfa il activity. There might be numerous types of pass-or-fail activities, however. Suppose we need a more specia lized class, such as one that determines a student's grade for a pass-orfail exam. The following PassFailExam class is an example. This class is derived from the PassFailActivity class. It inherits all of the members of PassFailActivity, including the ones that passFailActivity inhe ritS from GradedActivity. The PassFai1Exam class calculates the number of points that each question on the exam is wo rth, as well as the swdent's numeric score. (These files are stored in the Student SOllrce Code Folder Chapter lS\PassFailActivHy.)

M

Contents of PassFailExam _h 1

2

3

'ifndef PASSFAILEXAH H 'define PASSFAILEXAM_H #include "PassFailActivity. h"

4

5

class PassFailExam : public PassFailActivity

6

{

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

10 11 12 13

private: lot numQuestionSi II Number of questions double pointsEach; II Points for each question iot numMissed; /1 Number of questions missed public: II Default constructor

PassFailExam() : PasSFailActivity()

14 15

numQuestions = 0; pointsEach = 0.0;

16

numMissed '"' 0;

}

17

19

passFailActivity(mps)

21 22

{ set (questions , missed); }

23 24

/ / Mutator function void set( int , iot);

Ri

20

II Defined in PassFailExam.cpp

25

1/ Accessor functions double getNumQuestions() canst

28

{ return numQuestionS i }

an

26 27 29

30

double getpointsEach() canst { return pointsEach; }

31

ss

32

iot getNumMissed() canst { return numMissed; }

34

); #endif

Ha

33

36

az

/1 Constructor PassFailExam(int questions, int missed, double mps)

18

35

i

7 8 9

Inheritance, PolymorpniSom, and 'v'irtua\ tunctions

us uf

Chapter 15

Yo

924

Contents of PassFailExam. cpp Hncl ude "PassFailExam.h"

ad

1 2

5

11** ************************************************** **** II set function * II The parameters are the number of questions and the *

6

II number of questions missed.

7

11*** * *** ***************************** *********** ***** ****

3

m

4

m

8

9 10

M

uh a

11

void PassFailExam::set(int questions, int missed) { double numericScore; II To hold the numeric score

12 13 14

II Set the number of questions and number missed . numQuestions = questions;

15

numMissed

= missed;

l6

l7 18 19

II Calculate the points for each question . pointsEach = 100.0 I numQuestions;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

*


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

925

II Calculate the numeric score for this exam. numer i cScore = 100.0 - (missed * pointsEach) ;

22

23

II Call the inherited setScore function to set

24 25

1/ the numeric score .

setScore(numericScOre) i }

Yo

26

us uf

20 21

i

15.5 Class Hierarchies

az

The PassFailExam class inhe rits all of the PassFailActivi ty class's me mbers, including the ones that PassFailActivity inherited from GradedActivity. Because the public base class access spec ification is used, all of the procecred members of passFailAct i vity become protected members of PassFailExam, and all of t he public members of paSSFailActivity become public members of PassFailExam. Table 15路2 lists aU of the member variables of the PassFailExam class, a nd Tab le 15-3 lists all the member funclions. T hese include t he members that were mherited from the base classes.

Ri

Table 15-2 Access

Inherited ?

protected

poi ntsEach

protected

numMissed

protected

No No No

minPassingScore

protected

score

protected

M ember Functi on o f fh e Pass FailExarn Class

ss

Yes, fro m passFailActivity

Yes, from PassFailActivity, which inherited it from Gr adedAct i vity

Ha

Table 15-3

an

M ember Variable of the Pass Fa ilExam Class nurnQuestions

Access

In herited ?

public

public

No No No No

setMinFass i ngScore

public

Yes, from PassFailActivity

getMinPassingScore

public

Yes, from Pass~ailActivity Yes, from PassFailActivity

getNumQuestions get PointsEach

m

m

getNUrnMissed

ad

set

public

public

public

setScore

public

Yes, from PassFailActivity,which inherited it from GradedActivity

public

Yes, from PassFailAct i v i ty, which inherited it from

uh a

getLetterGrade

M

getScore

GradedActivity

Program 15-8 demonstrates the PassFailExam class. This file is also stored in the student source code folder Chapt er 15\PassFailActivity.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 926

Chapter 15

Inheritance, Polymorphism, and Virtual Functions

II This program demonstrates the PassFailExam class.

'include <iostream>

3 4

jinclude <iomanip> #include "PassFailExam.h"

5

using namespace std;

6

10 11

int main() { lnt questions; lnt missed;

1/ Number of questions

1/ Number of questions missed 1/ The minimum passing score

double minpassing;

12 13

II Get the number of questions on the exam .

14 15 16 17

cout «

"How many questions are on the exam? "i

questions;

Ri

cin »

19

20 21

an

/1 Get the number of questions the student missed . cout « "How many questions did the student miss? "; cin » missed;

18

/1 Get the minimum passing score. cout «

22 23

cin »

"En t er the minimum passing score for this test: minpassing;

";

ss

24

25

II Define a PassFailExam object. PassFailExam exam(questions, missed, minPassing)i

Ha

26 27

II Display ~he test results . cout « fixed « setprecision(l); cout « '"\nEach question counts « exam.getpointsEach() « points.\n'"; cout « "The minimum passing score is « exam.getMinpassingScore() « endl; cout « "The student·s exam score io « exam. getScore ( ) « endl; cout « "The student's grade is « exam.getLetterGrade() « endl; return 0;

28 29 30 31

35

36

37 )

.

.

.

.

m

33 34

.

m

ad

32

38 39

az

7 8 9

Yo

1

2

us uf

i

Program 15-8

Program Output with Example Input Shown In Bold

uh a

How many questions are on the exam? 100 [Enter] How many questions did the student miss? 2S [Enter] Enter the minimum passing score for this test : 60 [Enter]

M

Eac h quest i on count s 1.0 points . The minimum passing score is 60 . 0 The student ' s exam score is 75.0 The student ' s grade is p

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 927

i

15.6 Polymorphism and Virtual Member Functions

us uf

This program uses the PassFailEl<.am object to cal! the qetLet.t.erGrade me.mber fu[\crion in line 37. Recall that the PassFailActivity class redefines tbe getLetterGrade funcrion to report only grades of 'P' or 'F'. Because rhe PassFailExam cJass is derived from the PassFailActivity class, It inher its the redefined getLetterGrade function.

Yo

Software designe rs often llse class hierarchy diagrams. Eke a family tree, a class hietarchy diagram shows the inheritance relationships between classes. Figure 15-5 shows a class hiera rchy for the GradedActivity, FinalExam, PassFa i lActivity, and Pass Fail Exam classes. The morc general classes are toward the top of the tree and the more specialized classes are toward the bottom.

az

15 ~ 5

Figure

l

('>

PassFailActrvity

L -'

PassFailExam

Ha

ss

Fina!Exam

an

I

Ri

GradedAclivily

ad

Polymorphism and Virtual Member Functions

m

CONCEPT: Polymorphism allows an object reference variable or an object pointer to reference objects of different types, and to call the correct member fun ctions, depending upon the type of object being referenced.

Polymorphism

m

Look at the following code for a function named displayGrade: void displ ayGrade (const GradedActiv ity &activity)

uh a

{

cout « cout « « cout « «

setprecision ( 1) « fixed; ··The activity 's numeric sco r e is activity.getscore() « endl; "The activity's letter grade is . act~vltY · getLetterGrade()

«

endl;

M

)

This fu nction uses a canst GradedActivity reference variable as its parameter. When a GradedActivity object is passed as an argument [0 this function, the funct ion ca lls the object's getScore and getLetterGrade member functions to display the numeric score and letter grade. T he following code shows how we might call the function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

GradedActivity test(88 . 0); displayGrade(test);

II The score is 88 /1 Pass test to displayGrade

i

Inheritance, Polymorphism, and Virtual Functions

us uf

Chapter 15

928

Thjs code will produce the following output: The activity's numeric score is 88.0

The activity's letter grade is B

Yo

Recall that the GradedActivity class is also the base class for the FinalExam class. Because of the "is-a" relationship between a base class and a derived class, an object of the FinalExam class is nOt just a FinalExam object. It is also a GradedActivity objecr. (A final exam is a graded activity. ) Becau se of this relationship, we can also pass a Fina l Exam object to the displayGrade function . For example, look at the following code:

Ri

This code will produce the following output:

az

/1 There are 100 questions . The student missed 25. FinalExam test2{lOO, 25); displayGrade(test2) ;

The activity's numeric score is 75.0 The activity's letter grade is C

Ha

ss

an

Because the parameter in the disp layGra de function is a GradedAcUvity reference variable, it can reference any object rhat is derived from GradedActi vi ty. A problem can occur with this type of code, however, when redefined member functions are involved. For example, recalJ that the PassFailActivity class is derived from the GradedActivity class. The passFa i lActivity cla ss redefines the getLetterGrade funct ion. Although we can pass a PassFailActivity object as an argument to the displayGrade function, we wilt not get the results we wish. This is demonsrrared in Program 15-9. (This fi le is stored in the Student Source Code Folder Chapter 15 \PassfailActi v ity.)

Program 15-9

~i nc lu de <iostream> 'include <ioma ni p> lIinclude "PassFa ilAct ivit y.h" using names pace stdi

ad

1 2 3 4 5

II Function prototype void displayGrade(const GradedActivity &);

m

7 B

9

int main() {

II Create a PassFa i lAct ivi ty object . Minimum passing II score is 70.

uh a

10 11 12 13

m

6

passFailActivity test(70);

1.

II Set the SCOre to 72 . test.setScore(72)i

15

16

M

17

18 19

1/ Display the object's grade data . The letter grade II should be 'P'. What will be displayed ?

20

displayGrade(test); retur n Oi

21

22

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15.6 Polymorphism and Virtual Member Functions

i us uf

23 24

II *** **************.~*~~ *~**~~** ******~ ~~*~**~**** * *** ~~~ ~~* *****

25

II The d isplayGrade functi on displays a GradedActivity object's

26

II numeric score and l etter grade . ~ 11******··.* ··***** **** ******·**·** *** ** ** *** ******* ** ***********

cout « cout « « cout « «

31

32 33 34 35 36

setprecision ( 1) « fixed; "The activity's nume ric score is . activity . getScore() « endl; "The acti vity's letter grade is . act iv ity . getLe tterGrade ( ) « endl ;

Yo

void displayGrade(const GradedActivity &activity) {

~

az

27 28 29 30

929

}

Ri

Program Output The activity's numeric score is 72 , 0 The activity 's letter grade is c

an

As you can see from the exa mple o utput, the ge tLetterGrade member function retu rned 'C' instead of ' P'. This is because the Grade4Activity class's getLetterGra4e function was executed instead of [he PassFa ilActivity class's version of the func tion .

ad

Ha

ss

Tb is behavior happens because of rhe wa y C++ ma tches fu nct ion calls with the correct function . This process is known as binding. In Program 15-9, C++ decides a t compile time which version of the getLett erGrade fu nction to execute when it enCo unters the cal! to the function in line 35. Even though we passed a passFailActivity object to the d i splayGrade funct ion, the activity parameter in the displayGrade function is a GradedActivity reference variable. Beca use it is of the GradedActivi t y type, the COOl piler binds [he function call in line 35 with the GradedAc t i vity class's getLette rGr ade fu nction. When the program executes, it has already been determined by the compiler that the GractedActivity class's getLetterGrade hmctio n will be called. The process of matching a function ca ll with a function at compi le time is cal!ed static binding.

m

m

To remedy rhis, rhe getLetterGrade function can be made virtual. A virtual function is a member funcrion tbat is dynamically bound to function calls. In dynamic binding, C++ determines which function to ca ll at mnrime, depend ing on the type of the object responsible for the ca ll. If a GradedActivity object is responsible for the call, C++ will execute the GradedActivi ty: : getLetterGrade fun ction. If a PassFailActivity object is responsible for the call, C++ will execute the PassFailActi vi ty :: getLetterGrade function.

uh a

Virru al functio ns are declared by placi ng the key word virtual before the return type in the base class's function decla ration, such as

M

vi rtual char getLetterGrade() const;

This dedaration teUs tne compiler to expect getLetterGrade to be redefined in a derived do ss . Tbe compiler does nor b ind ca lls ro rhe func ri on with rh e actual function. Instead , it allows the program to bind calls, at runtime, to the version of the funct ion that belongs to the sa me cl ass as the object responsible for the ca ll.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 930

Inheritance, Polymorphism, and Virtual Functions

i

Chapter 15

us uf

NOTE : You place the virtual key word only in the function's declara tion or prototype. If the function is defined ou tside the class, yo u do not place th e virtual key word in th e

fLmction header.

1

fifndef GRADEDACTIVITY_ H

2

'define GRADEDACTIVITY_H

az

Contents of Grad e dActivity . h (Version 3)

J

/1 GradedAct ivity class declaration

4

13

an

11 12

class GradedActivity { protected ; double score ; /1 To hold the numeric score public: II Default constructor GradedActivity() { score = 0.0; }

ss

10

Ri

5

6 7 8 9

Yo

The following code shows an updated version of the GradedAct ivity class, with the getLetterGrade fun ction declared virtual. This file is stored in the Stude nt Source Code Folder chapter 15\GradedActivity version 3. The GradedActivity . cpp file has not cha nged, so it is not shown again.

14

1/ constructor GradedActivity(double S) { score = S; }

Ha

15 16 17

18

II Mutator function void setScore(double s) { score = s; }

ad

19 20 21 22

1/ Accessor functions double getScore() const { return score; }

23 24

25

m

2. 27

virtual char getLetterGrade() constj

}; fendif

m

28 29

uh a

The only change we have made to thi s class is ro declare getLetterGrade as virtual in lin e 27. This tell s the compiler not ro bind calls to getLetterGrade with the func tion at co mpile time. Instead, calls to the function will be bound dynamically to the fuonion at runtime.

M

When a member function is declared virtual in a base ciass, any redefined versions of the

funcrioll thar appear in derived classes automatically become virtual. So, it is not necessary to declare the getLetterGrade function in the Pa ssFailActivity class as virtual. It is still a good idea to declare the funcrion virtual in the passFailActivity class for documentation purposes. A new version of the PassFailActivity cla ss is shown here. This file is stored in the Student Sou(ee Code Folder Chapter lS\GradcdActivi t y Version 3. The passFailActivHy. cpp file has nO[ changed, so ir is nor shown again.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 931

Contents of PassFailActivity.h 1

2 .3

â&#x20AC;˘5

'ifndef PASSFAILACTIVITY H idefine PASSFAILACTIVITY H linclude "GradedActivity . h" class PassFailActivity : public GradedActivity

us uf

i

J 5.6 Polymorphism and Virtual Member Functions

(

7

protected: double minpassingScore; II Minimum passing score public : II Default constructor PassFailActivity(): GradedActivity() { minPassingScore = 0 . 0; )

9

10 11

12

az

8

Yo

6

13

II Constructor passFailActivity(double rnps) : GradedActivity() { minPassingScore ~ mps ; )

14

Ri

15 16 17

II Mutator void setMinPaseingScore(doub1e mpe) { minpassingScore = rnps; }

18

19

20

an

21 23 24 25

ss

II Accessors double getMinPassingScare() canst { return rninPassingScore: }

22

27

};

28

'endif

Ha

virtual char getLetterGrade() consti

26

Program 15-10

4

m

J

'include <ios tream> 'include <iomanip> h nc l ude npassFailActivity _h" using namespace stdi

m

1 2

5

II Function prototype void displayGrade(const GradedActivity &1;

uh a

6 7

ad

T he onl y cha nge we have made to this class is to declare getLetterCr ade as virtual in [me 26. Program 15-10 is identica l to Program 15-9, except it uses the corrected version of the GradedActivity and passFailActivity classes. This file is also stored in the student source code folder Chapter lS\GradedActivity Version J.

8

9

10 11

M

12 13 14

int main() {

II Create a passFailActivity object . Minimum passing II score is 70 .

passFailActivity test(70)i

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

(continued)

i

Program 15-10

Inheritance, Polymorphism, and Virtual Functions

/1 Set the score to 72. test.setScor e(72) ;

15

16 17

II Display the object's grade data . The letter grade

19 20 21 22

/1 should be 'P'. What will be displayed? displayGrade(test); return OJ

25 26 27 28

)

11* * · ' *.*** * * * * ** * * * * *·*·*** * * * *******·******···*****· ********* ** /1 The displayGrade function displays a GradedActivity object's *

/1 numeric score and letter grade.

az

23 24

Yo

18

*

1/**********·********** * ***** *** *************** **·*·** **** ******. void displayGrade{const GradedActivity ,activity)

30

(

Ri

29

cout «

31 32

setprecisio n (l) « fixed: MThe activity's numeric score is act i vity.getScore() « endl; "The activity's letter grade is

cout «

3' 35

..

an

« cout « «

33

36

us uf

Chapter 15

932

actlvity . getLetterGrade() «

)

ss

Program Output

endl;

Ha

The activity's numeri c score is 72. 0 The activity 's letter grade is P

m

Program 15-11

ad

Now that the getLetterGrade func tion is declared virtual, the program works properly. This type of behavior is known as polymorphism . The term polymorphism means the abil ity to take many for ms. Program 15-11 demonstra tes polymorphism by passing objecrs of the GradedActivity and PassFailExam classes to rhe d i splay Grade funcrion. This fi le is stored in the Stu dcm Source Code Folder Chapter lS\Grad edActivity Version 3.

'include <iostream> 'include <iomanip>

3 4 5 6 7 8

'include "PassPaiI Exam . h" using namespace std ;

uh am

1 2

9

M

10

11 12

II Funct i on prototype void displayGra de(COnst GradedActivity &); i nt main{)

(

II Create a GradedAc tivi t y object . The score is 88 . GradedActivity testl(88.0);

13

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 933

// create a PassFailExam object . There are 100 questions, II the student missed 25 of them, and the minimum passing 1/ score is 70. PassFailExam test2(100, 25, 70 . 0);

19 20 21 22 23

// Display t he grade data for both objects . cout « "Test 1: \n"; displayGrade(test1); II GradedActivity object cout « "\nTest 2:\n"; displayGrade(test2); II PassFailExam object return 0;

24

Yo

18

us uf

~4

15 16 17

i

, 5.6 Polymorphism and Virtual Member Functions

)

28 29

II The displayGrade function displays a GradedActivity object's * II numeric score and letter grade . *

)0

11 *********************** ****** *********************** ***********

Ri

az

25 26

31

36

37 J8

39

an

34

35

void displayGrade(const GradedActivity &activity) { cout « setprec ision ( 1) « fixed; cout « "The activity's numeric score is " « activity.getScore() « endl; cout « "The activity's letter grade is " « actlvity . getLe tt erGrade() « endl; )

ss

3~

11

Ha

Program Output Test 1: The activity's numeric scor e is 88 . 0 The activity's letter grade is B

ad

Test 2; The activity 's numeric score is 75.0 The activity's letter 9rade is P

m

Polymorphism Requires References or Pointers

m

The displayGrade function in Programs 15-10 and 15-11 uses a GradedActivity reference variable as irs parameter. When we call the fu nction, we pass an object by reference. Polymorphic behavior is not possible when an object is passed by value, however. For examp le, suppose the displayGrade function had been w ritten as shown here:

uh a

/1 Polymorphic behavior is not possible with this function. void displayGrade(cons t GradedActivi t y activity)

M

{

cout « cout « «

cout « «

setprecision(1) « fixed; "The activity's numeric score is ac tivity.getScore() « endl; "The activity'S letter grade is " activity . getLetterGrade ( ) « endl;

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

934

Inheritance, Polymorphism, and Virtual Functions

II Create a GradedActivity object. The score is 88. GradedActivity testl(88.D)i

us uf

i

In this version of the function the activity parameter is an object variable, not a reference variable. Suppose we call this vers ion of the function with the following code:

Yo

II Create a PassFailExam object. There are 100 questions, II the student missed 25 of them, and the minimum passing 1/ score is 70. PassFailExam test2(lOO. 25, 70.0);

Test 1:

Ri

This code will produce the fo ll owing oUCput:

az

II Display the grade data for both objects. cout ÂŤ "Test 1:\0": displayGrade(testl); 1/ Pass the GradedActivity object cout ÂŤ "\nTest 2:\n"; displayGrade( &test2); 1/ Pass the PassFailExam object

The activity's numeric score is 88.0

an

The activity'S letter grade is B

ss

Test 2: The activity's numeric score is 75.0 The activity's letter grade is C

Ha

Even though the getLetterGrade function is declared virtual, static binding still takes place beca use activity is not a refe rence variable or a poimer.

Alternatively we could have used a GradedActivity poimer in (he displayGrade function, as shown in Program 15- 12. This file is also stored in the Student Source Code Folder Chapter IS\GradedActivity Version 3.

2 3

linclude <iostream> 'include <iomanip> lIinclude "PassFailExam . h"

4

using namespace std ;

5

Function prototype void displayGrede(const GradedActivity *);

int main()

uh a

7 8 9 10

II

m

5

m

1

ad

Program 15-12

11 12

(

II Create a GradedActivity object. The score is 88. GradedAetivity test1(8B.O)~

13

16

II Create a PassFailExam object . There are 100 questions, II the student missed 25 ot them, and the minimum passing II score is 70 .

17

PassFailExam test2(100 , 25, 70.0);

14

M

15

18

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 935

II Display t he grade data for both objects.

us uf

19

i

15.6 Polymorphism and Virtual Member Functions

20

cout «

21 22

displayGrade(&testl); II ~ddress o f t he GradedActivity object c:out « "\nTest 2;\n";

23

displayGrade(&test2); return 0;

2>

II Address of the PassFailExam object

1

26

Yo

24

"Test 1; \ n";

27 11····*·**··*···*···*··*···*··**··*···*··***·*·····*** * •• * ••••••• 29

30 31 )2

II The displayGrade function displays a GradedActivity object's· II numeric score and letter grade. Th is version of the function· II uses a GradedActivity pointer as its pa r ameter. • .** * ••• ••••

11*••••

·.*.·* ..........·..··...........·* •• ••••••••·•·

az

28

33

void displayGrade(const GradedActivity ·activity)

34

{

«

37 38

cout « «

39

40

set precision(l) « fixed; "The activity's numeric score is activity->getScore() « endl; "The activity'S letter grade is " activity->getLetterGrade() « endl;

Ri

36

I

Ha

ss

Program Output Test 1 : The activity's numeric score is 88 . 0 The act ivity'S letter grade is B

an

cout « cout «

35

Teet 2. The activity' s numeric score is 75.0 The activity 'S letter grade is P

ad

Base Class Pointers

m

Pointers ro a base class may be assigned the add ress o f a derived class object . For exa mple, look a t the fo llowing code: GradedActivity .exam

=

new PassFailEXam(lOO, 25, 70 . 0);

m

This staternenr dyna mically allocates a PassFailExam o bject and assigns its address to exam, which is a GradedActivity pointer. We can then use the exam pointer to ca ll member fun ctions, as shown here;

uh a

cout « cout «

exam->getScore() « endl; exam- >getLetterGrade() « endl ;

Program 15· 13 is an example that uses base class poimers to reference derived class objects. This file is also stored in the Student Source Code Folder Chapter 15\

M

GradedActivity Version 3.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 936

Chapter 15 Inheritance, Polymorphism, and Virtual Functions

1

'~nclude

2

linclude <iomanip>

us uf

i

Program 15-13

J

#include "PassFailExam.h"

4 5

using namespace std;

6

II Function prototype

7

void d i splayGrade(const GradedActivity *); int main()

{

/1 Constant for the size of an array. const i nt NUM TESTS = 4;

11 12

az

8 9 10

Yo

<iostream>

13

/1 tests is an array of GradedActivity pointers. II Each element of tests is initialized with the /1 address of a dynamically allocated object .

17 18

GradedActivity *tests[NUM_ TESTSJ = { new GradedActivity(88.0),

21

new PassFailExam(50, 12,

22

};

23

an

new PassFailExam(lOO, 25, 70.0), new GradedActivity{67 . 0),

19

20

Ri

14 15 16

60.0)

{/ Display the grade data for each element in the array.

25

for (int count

26

{

cout « } return 0;

29 30 31

endl;

Ha

28

":\n":

}

ad

33 34

0: count < NUM_TESTS; count++)

cout « "Test t" « (count + 1) « displayGrade(tests{cOuntj)i

27

32

ss

24

11*** ************************************************* ***********

* * II uses a GradedAct ivity pointer as its parameter. * 11 ********************* *** **** ** ************** ******** ***********

37 38 39 40

void displayGrade(const GradedActivity *activity)

41

{

m

m

36

II The disp1ayGrade function displays a GradedActivity object's 1/ numeric score and letter grade. This version of the function

35

cout « cout «

setprecision(l) « fixed; "The activity'S numeric score is "

44 45

« cout «

activity->getscore{ ) « endl : "The activity's letter grade is "

46 4J

«

uh a

42 43

act ivity - >getLetterGrade() «

endli

M

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH ~unctions

937

i

15.6 Polymorphism and Virtual Member

us uf

Program Output

Test U: The activity ' s numeric score is 88.0 The activity's letter grade is B

Yo

Test '2 : The activity's numeric score is 75.0 The activity's letter grade is P Test t3!

az

The activity's numeric score is 67 . 0 The activity's letter grade is D

Ri

Test '4 : The activity's numeric score is 76.0 The activity's letter grade is P

new GraciedActivity{B8.0)

an

Let'S take a closer !ook at this program. An array named tests is defined In li nes 17 through 22. This is an array of GradedActivity pointers. The array elements are in itialized with the addresses of dynamically allocated objects. The tests[O) element is initialized with the ad dress of the GradedActivity object returned from th is exp ression:

ss

The tests [11 element is initialized with the address of the GradedActivity object returned from this expression:

Ha

new PassFailExam(100, 25, 70 .0)

The tests [2 J element is initialized with the address of the GradedActivity object returned from this expression: new GradedActivity(67.0)

ad

Finally, the tests(3] element is initialized with the add ress of the GradedActivity object returned from this ex pression;

m

new PassFailExam(50, 12, 60 . 0)

uh a

m

Although each element in the array is a GradedActivity pointer, some of the elements point to GradedActivity objects and some point to PassFailExarn objects. The loop in lines 25 through 30 steps through the array, passing each pointer element to the displayGrade function.

M

Base Class Pointers and References Know Only About Base Class Members Al though a base class pointer can reference objects of any class that derives from the base class there are limits to what the pointer can do with those objects. Recall that the Gra~edActivity class has, other than its constructors, only three member fllnctions: setScore, getScore, and getLetterGrade. So, a GradedActivity pointer can be used

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 938

Chapter 15

Inheritance, Polymorphism, and Virtual Functions

us uf

i

to call only those funct ions, regardless of the type of object it poi nts to. For example, look at the fo llowing code. Cradcd~ctivity

cout« cout « cout «

*exam = new PassFai l Exam(lOO , 25, 70.0) ; exam->getScore() «endl; II This works . exam->getLetterGrade() «endl; /1 This works . exam->getPointsEach() «endl; II ERROR! Won ' t work !

Yo

In chis code, exam is a GradedActivity pointer, and is assigned the address of a PassFailExam object. The GradedActivi ty class has only the setScore, getScore, and

az

getLetterGrade member fu nctions, so those are the only member functions tha t the exam variable knows how to execute. The last statement in this code is a call co the getPointsEa c h member function, which is defined in the PassFailE xa m class. Because tbe exam variable only knows about member functions in the Gr adedActivity class, it can not execute this functio n.

Ri

The "Is_a" Relationship Does Not Work in Reverse It is important to note that the "is-a" relationship does not work ill reverse. Although the statement "a final exam is a graded activi ty" is true, the statement "a graded activity is a

an

fina l exam" is not true. This is because nOt all graded activities are fin a l exams. Likewise, not all GradedActivity objects a rc Fi nalExam objects. So, the fo llowing code will not work.

ss

1/ Cr eate a GradedActivity object . GradedActivity *gaPointer

= new

GradedActivity(88.0) ;

Ha

// Error ! This will not work . *fePointer ~ gaPointer;

~inalExam

ad

You cannot ass ign the address of a GradedActivity ob ject to a FinalExam pointer. This makes sense because FinalExam objects Ilave capabilit ies that go beyond those of a GradedActivity object. Interestingly, the C++ compiler will let you make such an assignment if you use a type cast, as shown here:

m

II Create a GradedActivity object . GradedActivity *gaPointer = new GradedActiv i ty(88 . 0);

m

/1 This will work, but with limitations. FinalExam *fePointer = static cast<FinalExam *> ( gaPo i nter) ;

be pointi ng to a base but only the members

uh a

After this code executes, the derived class pointe r fePointer will class object. We can use the pointer to access members of [be object, that exist. The following code demonstrates:

M

1/ This wi l l work . The object has a getScore function . cout « fepointer->getScore{) « endl ;

II This will work . The object has a getLetterGrade function . cout « f e pointer- >getLetterGrade() « endl;

II This will compile , but an error will occur at runtime. II 'T'h'l obj ... ci:: d.., ..... n o+-. h",v<> '" 'JQ~p..,.; ... t"p. ...... h ;,_,... ,,10;<:>" _

cout «

fepointer - >getpointsEach() «

endl;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

939

i

15.6 Polymorphism and Virtual Member Functions

Yo

us uf

In this code fePointer is a FinalExam pointer, and it poims to a GradedActivity object. The first two cout statements work because the GradedActivity object ha s getS core and a getLetterGrade member functions. The last cout Statement will cause an error, however, because it calls the getPointsEach member function. The GradedActivity object does not have a getPointsEach member function.

Redefining vs. Overriding

az

Earlier in th is chapter you learned how a derived class ca n redefine a base class member function. When a class redefines a virtual function, it is said that the class overrides the function. In C++, the difference between overriding and rede finin g base class functions is thac overridden functions are dynamically bound, and redefined funct ions are statically bound. Only virtual functions can be overridden.

Ri

Virtual Destructors

ss

an

When you write a class with a destructor, and that class could potentially become a base class, you should always declare the destructor virtual. This is because the compiler will perform static binding on the destructor if it is not declared virtual. T his can lead to problems when a base class pointer or reference variable references a derived class object. If the derived class has its own destructor, it will nOt execute when the object is destroyed or goes out of scope. On ly the base class destructor will execute. Program 15-14 demonstrates.

1

2

'i nc lude <iostream> using names pace std;

3

Ha

Program 15-14

4 II Animal is a base class. class Animal

7 8 9

public; II constructor Animal () { cout « "Animal constructor executing. \n"; }

m

10

ad

5 6

11

14

15 16 17

II The Dog class is derived from Animal

18

class Dog : public Animal

19 20 21

public:

}

M

uh a

};

m

II Destructor - Animal ( ) { cout « "Animal destructor executing. \0";

12 13

22 23

{

II Co n st ructor

Dog(l: Animal() { cout « "Dog constructor execut i ng . \n"; }

24

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 15w14

Inheritance, Polymorphism, and Virtual Fu nctions

(continued)

25

II Destructor

26

-Dog()

27 28

{ cout «

i

Chapter 15

us uf

940

"Dog destructor executing.\n" ; }

};

30 31

// ** * ***** *************************** *** *** .*.j****

II main f unction

//********* * ****** * ************* *** ** ***** * ** *** ***

34 35 36 37

int main () { 1/ Cr eate a Dog object , referenced by an / / Animal pointer.

38

Animal *myAnimal : new Dogi

40

II Delete the dog object .

41

de l ete myAnimal; retur n 0 ;

Program Output

Animal constructor executing. Dog constructor executing. Animal destructor executing.

an

)

ss

42 43

Ri

39

az

32 33

Yo

29

Ha

This program declares two classes: Animal and Dog. Anima l is the base class an d Dog is

m

Program 15-15

ad

the derived class . Each class has its own constructo r a nd destructor. In line 38, a Dog object is crea ted an d its address is stored in an Animal pointer. Both the Animal and the Dog co nstructors execute. In hne 4 1 the o bjec t is deleted. When this sratt:menr executes, however, only the Animal destructor executes. The Dog desrrucror does nor execute because the o bject is referenced by an Animal poimer. We can fix th is problem by decla ring the Animal class destructor virtual, as shown in Program 15-15.

'include <iostream> using namespace std;

4 5

II Animal is a base c lass. class Animal

6

{ public:

uh a

m

1 2 3

7

8

II Constructor

9

Anima l()

10

{ cout «

"Animal constructor executing . \ n"; }

M

11

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

, 5.6 Polymorphism and Virtual Member Functions

II Destructor virtual -Animal() { cout « ~Animal destructor executing.\n"; }

12 13 14 15

us uf

i

941

};

17 18 19 20 21 22 23

II The Dog class is derived from Animal class Dog : public Animal { public: II Constructor Dog(): Animal() { cout « ~Dog constructor executing.\n"; } II Destructor -Dog() { cout « HDog destructor executing.\n " ; }

25 26

Ri

31 32 33

}:

11**************************-*-********-**-******** II main function • 11******-**---*****-****--*-***--******-*****-*****

34

int main ( )

35 36

{

II Create a Dog object, referenced by an II Animal pointer.

37 38 39

~

new Dog;

Ha

Anima l *myAnimal

II Delete the dog object . delete myAnimal; return 0 :

40

41 42 43

an

29 30

ss

27 28

az

24

Yo

16

)

ad

Program Output

m

Anima l constructor exe cuti ng , Dog constructor executing. Dog destructor executing. Animal destruc tor executing .

uh a

m

The only t hing that has changed in this program is that the Animal class destructor is declared virtual in line 13. As a result, the destructor is dynamically bound at runtime. When t he Dog object is destroyed, both the Animal and Dog dest ructors execute.

M

A good p rogramming practice to follow is that any class that has a virtua l member function should also have a virtual destructor. If the class doesn't require a destructor, it should have a virtual destructor that performs no statements. Remember, when a base class function is declared virtual, all overridden versions of the function in derived classes automatica lly become virtua l. Includ ing a virtual destructor in a base class, even one that does nothing, will ensure that any derived class destructOrs will also be virtual.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 942

Inheritance, Polymorphism, and Virtual Functions

us uf

i

Chapter 15

Abstract Base Classes and Pure Virtual Functions

Yo

CONCEPT: An abstract base class cann ot be instantiated, but o ther classes are derived from it. A pure virtual fun ction is a virtual member fun ction of a base class that must be o verridden . When a cl ass contains a pure virruaJ function as a m ember, th at class b ecom es an ab s tract base class.

Sometimes it is helpful to begin a class hierarchy with an abstract base class. An abstract

az

base class is not instantiated itself, but serves as a base class for other classes. The abstract base class represents the generic, or abstract, form of all the classes that are derived from it.

an

Ri

For example, consider a facrory that manufactures airplanes. The facto r y does not make a generic airp la ne, but makes three specific types of p lanes: twO different models of propdriven planes, and one com muter jet model. The computer software that catalogs the planes might use an abstract base class called Airplane . That class has members representing the common characteristics of aU airplanes . In addition, it has classes for each of the three specific airplane models the facto ry manufactures . These classes have members representing the unique characteristics of each type of plane. The base class, Airplane, is never instantiated, but is used to derive the other classes.

ss

A class becomes an abstract base class when one or more of its member fu nc tions is a pure virtual (unction. A pure virtual function is a virtual membe r funct ion declared in a manner si milar to the fo llowing:

Ha

virtual void shoWlnfo{)

=

0;

ad

The = 0 nocation indicates that shOWlnfo is a pure virtual functio n. Pure virtual functions have no body, or definition, in the base class. T hey must be overridden in derived classes. Additiona ll y, the presence of a pure virrual funct ion in a class prevents a program from instantiating the class. The compile r will genera te an error if you attempt to define an object of an abstract base class. For example, look at the followi ng abstract base class Student. It ho lds data common to

m

all students, bur does not hold all rhe d ara needed for students of specific majors.

m

Contents of student. h /1 specification file for the Student class

3

jifndef STUDENT_ H 'define STUDENT H

4

#include <cstr i ng>

5 6

II Constants for array sizes

uh a

1

2

M

7

8

// For strcpy

const int NAME SIZE = 51i const int ID S I ZE = 21;

9

10

class Student

11

{

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 943

15

16 17 18 19 20 21 22

protected: II Student name char namelNAME_ SIZEJ ; char idNumberIID_SIZE Ji II Student ID int yearAdmitted; II Year student was admitted public : II Default constructor Student () { name[O] = '\0'; idNumber(O] = '\0'; yearAdmitted = 0 ; }

us uf

13 14

Yo

12

i

, 5.7 Abstract Base Classes and Pure Virtual Functions

23

II Constructor Student(const cha r *n, canst char wid, int year) { set{n, id, year); }

az

24 2S 26 27

33

II The set function sets the attribute data . void set(const char *n, const char wid, int year) { strncpy(name, n, NAME_SIZE); II Copy the name name[NAME_SIZE - 1] = '\0'; II Place a null character strncpy(idNumber, n, IO_S1ZE); II Copy the 10 number idNumber [ IO_SIZE - 1) = '\O'i II Place a null character II Assign year admitted yearAdmitted = year; }

3S 36 37

II Accessor functions canst char *getName() canst { return name; }

39 40

canst char *getIdNUm() const { return idNumberi }

28

Ri

29

30

31 32

an

3.

Ha

ss

3. 41

42 43

int getYearAdmitted() canst { return yearAdmitted;

44

II Pure vi rtual function virtual int getRemainingHourS() const - 0;

ad

45 46 47

};

48

jendif

m

m

T he Student class contains members for storing a student's name, ID number, and year admitted. It also has constructors and a mutator function fo r setting values in the name, idNumber, and yearAdmitted members. Accessor functio ns are provided that return the values in the name, idNumber, and yearAdmitted members. A pure virtual function named getRemainingHours is also declared.

M

uh a

T he pure virtual fu nction must be overridden in classes derived from the Student class. It was made a pure virtual function because this class is intended to be the base fo r classes that represent students of specific majors. For example, a CsStudent class m ight hold the data for a computer science srudent, and a BiologyStudent class might hold the data for a biology student. Computer science students must take courses in different disciplines than those taken by biology students. It stands to reason that the CSStudent class will calculate the number of hours taken in a different manner than rhe BiologyStudent class . Let's look at an example of the CsStudent class.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

944

Inheritance, Polymorphism, and Virtual Functions

II Specification file for the CsStudent class 'ifnde f CSSTUDENT_H

3

~define

4

iinclude "Student . h"

5 6

CSSTUDENT_H

/1 Constants for required hours

us uf

1 2

i

Contents of CsStudent. h

canst int MATH_ HOURS == 20 ; /1 Math hours const int CS_ HOURS = 40; II Computer science hours canst int GEN ED HOURS = 60; /1 General Ed hours

11 12 13

class CsStuden t

: public Student

10

private: int mathHours; int csHours; int genEdHours;

17 18

public :

15

az

{

II Hours of math taken /I Hours of Computer Science taken II Hours of general education taken

/1 Default constructor

20

CsStudent() : Student()

21 22 23

{ mathHours 0; csHours '" 0 ; genEd Hours = 0;

=

2.

an

19

Ri

,.

Yo

7 8 9 10

}

26

Student(n,

28

{

29 30

31

id, year) mathHours = 0; csHours = 0; genEdHours = 0 i }

Ha

27

ss

1/ Constructor csStudent(const char *n, canst char *id, int year)

25

1/ Mutator functions void setMathHoUrs(int rnh) { mathHours ." mh; }

ad

32 33 34 35

void setCs Hours (int csh) { csHours = csh; }

36

m

37

38

39

void se tGenEdHour s(int geh)

m

40

{ genEdHours "" geh;

}

41

M

uh a

42 43

II Ove~ridden getRemainingHours function, II defined in CsStudent . cpp virtual int getRemainingHourS() can st;

44 45

};

46

'end if

This file declares the following const int member variables in lines 7 through 9: MATH_HOURS, CS _HOURS, and GEN _ ED_HOURS. These varia bl es hold the required number of math, computer science, and general education hours for a computer science studem. The

CsStudent class, which derives from the Student class, declares rhe follow ing member variables in lines 14 through 1 6: mathHours, csHours, and genEdHours. These variables

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 945

i

, 5.7 Abstract Base Classes and Pure Virtual Functions

us uf

hold the number of math, computer science) and general education hours taken by the student. Mutator functio ns are provided to store values In these variables. In addition) the class overrides the pure virtual getRemainingRours function in the CsStudent.cpp file.

Contents of CsStudent . cpp

, 3

tinclude <iostream> 'include "CsStudent.h" using namespace std;

Yo

1 2

8

II**** * *********~* * *********·*********·*********** * ***

6

az

7

//**** ********************** * ************************* // The CsStudent::getRemainingHours funct ion returns * /1 the number of hours remaining to be take n. •

5

9

int CsStudent::getRemainingHours() const

11

{

12

int reqHours, remainingHours;

13 14

15

II Total required hours

II Remaining hours

II Calculate the required hours. reqHours ; MATH_HOURS + CS_HOURS + GEN_ED_HOURS;

an

16 17

18

II Calculate the remaining hours . remainingHours = reqHours - (mathHours + csHours + ge nEdHOurS)i

19

ss

20 21

)

Ha

II Return the remaining hours . return remainingHours;

22 23 24

Ri

10

Program 15-16 provides a simple demonstration of the class.

5 6 7

8

int main()

II Create a CsStudent object f or a student . CsStudent student( "Jennifer Haynes", "167w9B337", 2006);

uh a

9 10

II This program demonstrates the CsStudent c l ass, which is // derived from t he abstract base class, Student . 'include <iostream> 'include "CsStudent . h" usi ng namespace std;

m

2 3 4

m

1

ad

Program 15-16

11 12

13

I' IS

M

16

II Store values for Math, Computer Science, and II Ed hours. student.setMathHoUrs(12): II Studen t has taken s t udent . setCsHours( 2 0) ; /I Student h., taken student . setGenEdHOUrS(40)i /I Student has taken

Genera l 12 Math hours 20 CS hours

40 Gen Ed hours

17

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

Inheritance, Polymorphism, and Virtual Functions

Program 15-16

i

(continued)

1/ Display the number of remaining hours. cout « "The student" « student.getName{) «needs to take " « student . getRemainingHours ( ) « " more hours to graduate. \0 ";

18 19

20 21

22

Yo

return 0;

23 24

us uf

946

)

az

Program Output The student Jennifer Haynes needs to take 48 more hours to graduate .

Remember the followlOg points about abstract base classes and pure virtual functions: When a class contains a pure virtual function, it is an abscracr base class.

Pure virtual funct ions are declared with tb e '" 0 notation.

• • •

Abstract ba se classes cannot be instantiated. Pure virrual func tions have no body, or definition, in the base class. A pure virtual fu nction must be overridden at some poine in a derived class m order fo r it to become nonabstracL

an

Ri

~ Checkpoint

Explain the difference between overloading a function and redefinmg a function.

1S .10

Explain the difference be tween sta tic binding and d ynarllic billdillg.

15.11

Are virtual functions sratically bound or dynamically bound?

15.12

What wi ll the fo llowing program d isplay?

Ha

ss

15.9

*include <iostream.> using namespac e std;

ad

class Firs t {

m

protected: int a; public: First(int x = 1)

M

uh a

m

{ a

)

= Xi

}

int getVal() { return a

j

}

:

class Second

public First

{

private; i nt b ;

public:

Second(int y = 5) { b " y: } int getVal ( ) { return b; }

):

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15.7 Abstract Base Classes and Pure Virtual Functions

us uf

i

int main ( ) (

First objectl;

Second object2; cout « objectl .g etVal() « cout « object2.getVall) « return 0;

endl ; endl :

Yo

)

15.13

What will the following program display?

az

'include <iostream> usi ng names pace std i class First

Ri

{

protected: i nt a; pUblic: First(int x { a = Xi

1) }

an

void twist ( ) {a*=2:}

int getVal() ( twist();

return a ;

class Second

}

ss

) ;

public First

(

Ha

private : int bi public: Second(int y { b -

y;

=

5)

)

void twist()

ad

{b*::10;}

);

m

int main() (

uh a

m

First objectl; Second object2;

M

15. 14

947

caut « abjectl . getval() « endl; caut« object2.getVal{) «endl : return 0;

What will the following program display? 'include <iostream> using namespace std; class First { protected : int a;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 948

Chllpter , 5 Inheritanc.e, Polymorphism, and Virtual function!)

publ.ic!

i

= 1)

us uf

First(int x

{ a = X; }

virtual void twist(J {a'll=2;}

int getVal()

,

{ twist(); return a; }

class Second

Yo

}

public First

)

,

int main()

Ri

private: int bi public: Second(int y = 5) { b = Yi } virtual void twist() {b*"' lO:}

az

{

{

an

First objectl; Second object2;

objectl.getVal() « object2.getVal() « return 0;

ss

cout « cout «

15.15

Ha

)

endl; endl;

What will the following program display? 'include <iostream> using names pace std; {

ad

class Base

protected : int basevar;

uh am

m

public : 8ase(int val

= 2)

{baseVar

val;}

int getvar()

{ return basevar; }

),

class Derived

public Base

{

M

private: int derivedVar;

public: oerived(i nt val = 100) (derivedVar val; int getVar { 1

{ return derivedVar; } );

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH , 5.8 Multiple Inheritance

us uf

i

int main ( ) {

949

Base *optr; Derived object;

optr = &object; optr->qetVart) ÂŤ

cout ÂŤ

endl j

return 0 :

Yo

}

Multiple Inheritance

az

CONCEPT: Multiple inheritance is when a derived class has two or more base classes.

an

Ri

Previously we discussed how a class may be derived from a second class rhar is itself de rived from a third class. The series of classes establishes a cha in of inheritance. In such a scheme, you might be tempted to think o f the lowest class in the chain as having multiple base classes. A base class, however, shou ld be thought of as the class thar another cla ss is directly derived from. Even though there may be seve ral classes in a chain, each class (below the topmost class) only has one base class.

ss

Another way of combining classes is through multiple inheritance. Multiple inheritance is when a class has twO Or more base classes. This is iHustrated in Figure 15-6.

Ha

Figure 15-6

~T I Class C

ad

[

m

m

in Figure 15-6, class C is directly derived fro m classes A and B, and inherits the members of both. Neither class A nor B, however, inherits members from the other. Their members are only passed down to class C. Let's look at an exam pl e of multip le inheritance. Consider the two classes decla red here:

Contents of Date. h /1 Specification file for the Date class

'ifndef DATE H

3

,

' define DATE H

5 6

class Date {

M

uh a

1

2

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

9 10 11 12 13 14 15 16 17

i

protected: int day;

S

int month; int year; public : II Default constructor Date(int d, int m, int y) { day = 1; month'" 1; year -

1900 j }

/ I Constructor

Date(int d, int m, i nt y) { day = d; month = m; year'" Y i

18

}

20

/1 Accessors

21 22

int getDay () canst { return day; }

az

I.

24 25

int getMonth() const { return month; }

26 27 28

int getYear() canst { return year; }

2 3

II Specification file for the Time class 'iindef TIME H 'define TIME H

4

5

class Time

Ha

1

{

7 9 10

protected : int hour; int min; int sec i

11

public;

m

ad

6

8

ss

Contents of Time. h

an

}; 'endif

Ri

23

29 30

1/ Default constructor

13 14 15 16 17

Time() { hour '" 0; min ... 0 i sec -

uh am

12

18

us uf

7

Inheritance, Polymorphism, and Virtual Functions

Yo

Chapter 15

950

0;

)

II Constructor Time(int h, int m, int 5) { hour"" h i min"" m; sec"" s; }

M

1.

20

II Accessor functions

21

int getHour() const

22

{ return hour;

}

23

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 951

24

int getMin() const { return min ; }

27

int getSec() const

2.

us uf

25

i

15.8 Multiple Inheritance

{ return sec; }

28 29

};

30

'endif

Yo

These classes are designed to hold inregers that represent the date and time. They both can be used as base classes for a third class we will call DateTime:

Contents of Dat e Time. h

4

5

â&#x20AC;˘

7 8 9

10

az

3

1/ Specification file for the DateTime class lifndef DATETIME H

tdefine DATETIME H #include "Date.h" Unclude "Time.h" 1/ Constant for string size canst int DT_ SIZE - 20;

Ri

2

class DateTime : public Date, public Time

an

1

{

12 13 14

protected: char dateTimeString[OT_SIZE) i pUblic: // Default constructor OateTime();

15 16

ss

11

Ha

17

// Constructor DateTime(int, int, int, int, int, int);

18

19 20

II Accessor function canst char *getDateTime(} const { return dateTimeString; }

21

23 24 25

ad

22 );

'endif

m

In line 10, the first line in the DateTime declaration reads class DateTime : public Date, public Time

uh a

m

Notice there are two base classes listed, separated by a comma. Each base class has its own access specification. The genera l format of the first line of a class declaration with multiple base classes is

M

class DerivedClassName

AccessSpecification BaseClassName,

AccessSpecification BaseClassName [ , ... 1

The notation in the square brackets indicates that the list of base classes with their access specifications may be repeated. (It is possible to have several base classes.)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

952

Inheritance, Polymorphism, and Virtual Functions

3

II Implementation file for the DateTime class # include <cstring> II For strcpy and strcat Hnclude <cstdlib> II For itoa tinclude "DateTime . h"

5

6

II Constant for temp array size

7

const int TEMP_SIZE

= 10;

Yo

8 9

us uf

2

i

Contents of OateT ime . cpp

1/**********************·************* ************

10

1/ Default constructor

11

1/********************************** * *************

12 13

DateTime::DateTime()

14

(

19

az

strcpy(dateTimeString,

"1/1/1900 0 : 0:0");

}

Ri

15 16 17 18

: Date(), Time()

11-···-------------------------------------------1/ Constructor • 1/***********************************.*·********** DateTime :: DateTime(int dy, i nt mon, int yr, int hr, int mt, int se) Date(dy, mon , yr), Time(hr, mt, se)

24

{

an

20 21 22 23

II Temporary work area for itoa()

char temp(TEMP_SIZE];

27

II Store the date in dateT i meString, in the form MM/DO/YY strcpy(dateTimeString, itoa(getMonth(), temp, TEMP_SIZE»); strcat (dateTimeString , "I") i strcat(dateTimeString, itoa(getDay(), temp, TEMP_SIZE»); strcat(dateTimeString, "/tI); strcat{dateTimeString , itoa(getYear(), temp, TEMP_SIZE»; strcat(dateTimeString,"") i

ss

25 26

Ha

28 29 30 31 32 33

ad

3.

II Store the time in dateTimeString, in the form HH:MM:SS strcat(dateTimeString, itoa(getHour(), temp, TEMP_SIZE»: strcat(dateTimeString, ";"); strcat(dateTimeString, itoa(getMin(), temp, TEMP_ SIZE»; strcat(dateTimeString, ":"); strcat(dateTimeStri ng, itoa(getsec(), temp, TEMP_SIZE»;

m

m

35 36 37 38 39 40 41

}

uh a

The class has t wO constructors: a default constr uctor and a constructor that accepts arguments for each component of a date and time. Let's look at the function header for the

default consrrucroc, in line 13: : Date(), Time()

M

DateTime::DateTime()

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 953

, 5.8 Multiple Inheritance

us uf

i

After the DateTime constructor's parentheses is a colon, foHowed by calls to the Date constructor and the Time constructor. The calls are separated by a comma. When using multiple inheritance, rhe general forma t of a derived class's constructor header is

DerivedClasSName(parameterList) : BaseClasSName(ArgumentList) , BaseClaSSName( ArgumentList)I, ... 1

Yo

Look at the function header for the second constructor, which appears in lines 22 a nd 23:

DateTime::DateTime(int dy, int mon , int yr, int hr, int mt, int sel : Date(dy, mon, yr), Time(hr, mt, SC)

az

This DateTime constructor accepts arguments for the day (dy), month (man), year (yr), hour (hr), minute (mt) , and second (sc). The dy, mon, and yr parameters are passed as arguments ro the Da t e consrructor. T he hr, mt, and se parameters are passed as arguments to the Time constructor.

Ri

The order that the base class constructor calls appea r in the list does nOt marreroThey are always called in the order of inheritance. That is, they are always ca lled in the order they are listed in the first line of the class declaralion. Here is line 10 from the DateTime. h file:

an

class DateTime : public Date, public Time

ss

Because Date is listed before Time in the DateTime class declaration, the Date constructor wi ll always be called first. If the classes use destructors, they are always ca lled in reverse order of in heritance. Program 15- 17 shows (hese classes in use. Program 15-17

3 4 5 6 7 8

II This program demonstrates a class with multiple i nheritance. #include <iostream> 'include "DateTime.h" using namespace std ;

Ha

2

int main()

ad

1

(

Define a DateTime object and use the default constructor to initialize it. DateTime emptyDaYi II II

9

m

10 11

II Display the object'S date and time. cout « emptyDay . getDateTime() « endl ;

12

m

13 14

16

II Define a DateTime object and initialize it II with the date 2/4/60 and the time 5 : 32:27 .

17

DateTime pastDay(2, 4, 60, 5, 32, 27);

uh a

15 18

19

1/ Displ ay the object'S date and time. cout « pastDaY . getDateTirne{) « endl; return 0 ;

20

21

M

22

)

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 954

Chapter 15

Inheritance, Polymorphism, and Virtual Functions

Program 15-17

us uf

i

(continued)

Program Output 1/111900 0:0:0

4 /2/ 60 5:32:27

Yo

NOTE: It shou ld be noted that multiple inheritance opens the opportunity for a derived class to have am biguous members. Tha t is, two base classes may have member va riables or functions of the same name. In situations like these. the derived class should always redefine or override the membe r functio ns. Calls ro the member functions o f the appropriate base

~

Ri

az

class can be performed within the derived class Llsing the scope resolution operator(::). T he derived class can also access [he ambiguously named member variables of the correct base class using the scope resolution operator. If these steps aren't taken, the compiler wi ll generate an error when i( ca n't (eil which member is being accessed.

Checkpoint 15.16

D oes ( he following d iagram depict mu ltip le inherita nce or a chain of inheritance?

~ Class A

an

~r;(:;-:ia~SS"'B--'1 ("""ia~ ss7(' I

15.17

ss

r i e

Ooes the foll owing d iagra m depict mu ltiple in hf'rita nce or a ch:1in of inherita nce?

~

Ha

I Class A

1

(iass (

Class B

1

Exa mine the fo llow ing classes. The ta ble lists the variables that are members of the Third class (some are inherited). Complete the (a ble by filling in the access specification each member will have in the Third class. Write "inaccessible" if a member is inaccessible to the Third class.

ad

15. 18

---1

class First

m

{

M

uh a

m

private ;

i nt a ;

protected : double bi public:

long c;

};

class Second protected First { private: int d; protected : double e; public : long fi };

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15.8 Multiple Inheritance

public Second

i

class Third

95 5

us uf

{

private : int g; protected : double h; pUblic: long i;

Yo

} ;

Member Variable

Access Specification in Third Class

a b

az

c d

Ri

e f

g h

Examine the following class declarations:

ss

15.19

an

i

class Van {

Ha

protected: int passengers; public: Van(int p) (passengers p;} } ;

{

ad

class FourByFour

} ;

Write the declaration of a class named sportutility. The class should be derived from both the Van and FourByFour classes above. (This should be a case of mu ltiple inheritance, where both Van a nd FourByFour are base classes.)

M

uh a

m

m

protected : double cargoWeighti public: FourByFour(float w) { cargoWeight ; W; }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

956

Inheritance, Polymorphism, and Virtual Functions

us uf

i

Review Questions and Exercises Short Answer 1. What is an "is a" relationship?

2. A program uses two classes: Dog and Poodle. Which class is the base class and which is the derived class?

Yo

3. How does base class access specification differ from class member access specification?

4. What is the difference between a protected class member and a private class member? 5. Can a derived class ever directly access rhe private members of its base class? 6. Which constructor is called fi rst, that of the derived class or the base class?

az

7. What is the difference between redefining a base class function and overrid ing a base class funct io n?

Ri

8. When does static binding take place? When does dynamic binding take place?

9. What is an abstract base class?

10 . A program has a class Potato, which is derived from the class vegetable, which is derived from the class Food. Is this an example of multiple inheritance? Why or why not?

class Pet : public Dog

an

11. What base class is named in the line bel ow?

ss

12. What derived class is named in the line below? class Pet : public Dog

Ha

13. What is the class access specification of the base class named below? class Pet : public Dog

14. What is the class access specification of the base cl ass named below?

ad

class Pet : Fish

15. Protected members of a base class are like _ __ __ members, except they may be accessed by derived classes.

m

m

16. Complete the tab le below by filling in private, protected, public, or inaccessible in the right-hand column: In a private base class, this base class

uh a

MEMBER access specification...

... becomes this access specification in the derived class.

private protected

M

public

17. Complete the table below by filling in private, protected, publ ic, or inaccessible in the right-hand column:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

... becomes this access specification in the derived class.

us uf

[n a protected base class, this base class MEMBER access specification . ..

957

private protected

public

In a public base class, this base class MEMBER access specification . ..

Yo

18. Complete the table below by filling in private, protected, public, or inaccessible in the right-hand column: ... becomes this access specification in the derived class.

az

private protected

Ri

public

Fill-in-the-Blank

19. A derived class inherits the _ _ _ _ of its base class.

an

20. When borh a base class and a derived class have constructors, the base class's con(first/last). structor is called

ss

21. When both a base class and a deri ved class have destructors, the base class's constructor is called (first/last).

Ha

22. An overridden base class function may be called by a func tion in a derived class by using the operator. 23. When a derived class redefines a function in a base class, which version of the fun ction do objects that are defined of the base class call? ___ __ 24. A(n) --,--,___ member function in a base class expects to be overridden in a derived class . binding is when the compiler binds member function calls at compile time.

ad

25. 26.

is when member functions in a class hierarchy behave differently, depending upon which object performs the ca lL

m

27.

binding is when a function call is bound at runtime.

m

28. When a pointer to a base class is made to point to a derived class, the pointer ignores any the derived class performs, unless the fu ncti on is _____

29. A(n) _ _ _ _ class can not be instantiated.

uh a

30. A(n)

function has no body, or defini tion, in the class in which it is declared.

31. A(n) of inheritance is where one class is derived from a second class, which in turn is derived from a th ird class.

M

32. _ ____ is where a derived class has two or more base classes.

33. In multiple in heritance, the derived class should always ___ __ a function thar has the same name in more than one base class.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 9 58

Chapter 15

Inheritance, Polymorphism, and Virtual Functions

i

Algorithm Workbench

us uf

34. Write the first line of the decla ration fo r a Poodle class. Th e class should be derived from the Dog cI:1sS with public base cla ss access. 35. Write the first line of the declaration for a SoundSystem class. Use multiple inherita nce to base the class on the CDplayer class, the Tuner class, and the CassettePlayer class . Use public base class access in rill cases.

Yo

36. Suppose a class named Tiger is derived from both the felis ChlSS and rhe Carnivore class. Here is th e first line of the Tiger class declaration: class Ti ger: public Felis, public Carnivore Here is the fU llction header for the Tiger constr uctor:

Which base class constructo r is called fi rst,

az

Tiger(lnt x, int y) : Car nivore(x) , Fel is(y) Ca rn iVore

or

Felis?

Ri

37. Write the declaration for class B. Th e class's members should be

m, an integer. This varia ble shou ld not be accessible to code outside the class or to member functions in any cl,l SS derived from c1<lSS B. n, an inreger. T his variable should not be accessible to code ourside the class, bur shoul d be accessible to member fun ctions in any class derived from class B. setM, getM, setN, and getN. These are the set and get functions for the membe r Varil.lbles m and n. T h e~e fUllction~ sho uld be accessible to code outs ide tbe class. calc, a public virtual member function that returns rhe va lue of m rimes n.

an

• •

ss

m

ad

Ha

Nex t write the declarat ion for class D, which is derived from class B. The class's mem ~ bers should be • q, a float. This variable sho uld nOt be accessi ble to code outside the class but should be accessib le to mem be r functions in any class derived from class D. • r, a float. T his variable should not be accessible to code outside the class, but shou ld be accessible to mem ber functions in any class derived from class D. • setQ, getQ, setR, and getR. These arc the set and get functio ns for th e member variab les q and r. These functions shoul d be accessible ro code outside the ci<lss. • calc, a pub lic member function that over rides the base class calc functio n. Th is function should return the value of q times r.

True or False F

m

38. T

M

uh a

39. T

F

40. T 41. T

F

42. T

F

43. T

F

F

The base class's access specificarion affects the way base class member func~ tions may access base class member variables. The base class's access specification affects the wa y the deri\'cd cla ss inherits members of the base class. Private members of a private base class become inaccessible to the derived class. Pu blic members of 3 privare base class become private members of rhe derived class. Protected members of a private base class beco me public members of the derived class. Public members of a protected base class become private members of the derived class.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

959

F

Private members of a protected base class become inaccessible to the derived class.

45. T

F

Protected members of a public base class become public members of the derived class.

46. T

F

The base class constructor is called after the derived class constructor.

47. T

F

The base class destructor is called after the derived class destructor,

48. T

F

It isn't possible for a base class to have more than one constructor.

49. T

F

50. T

F

Arguments are passed to the base class constructor by the derived class constructor. A member function of a derived class may not have the same name as a mem-

F

us uf

Yo

az

F

ber function of the base class. Pointers to a base class may be assigned the address of a derived class object. A base class may nOt be derived from another class.

Ri

51. T 52. T

i

44. T

Find the Errors

Each of the class declarations and/or member function definitions below has errors. Find as many as you can.

an

53. class Car, public Vehicle {

public: Car() i

ss

-Car() i

Ha

protected: int passengers; }

54. class Truck, public : Vehicle, protected {

ad

private: double cargoWeighti public: Truck() ; -Truck() i

m

};

55. class SnowMobile

Vehicle

{

uh a

m

protected: int horsePower; double weight; public: SnowMobile(int h, double wI, Vehicle(h) { horsePower = h; } -SnowMobile ( ) ;

};

M

56. class Table : public Furniture {

protected: int numSeats;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Inheritance, Polymorphism, and Virtual Functions

public : Table(int n)

{ numSeats )

Furniture (numSeats)

!

= n;

i

Chapter 15

}

us uf

960

-Table() ;

,

57. class Tank : public Cylinder (

void setContents(double); void setcontents(double);

,

Ri

58 . class Three : public Two : public One {

protected:

int x;

an

,

public: Three(int a, int b , lnt e), Two(b), Three(c) { x '" a; } -Three ();

ss

)

az

)

Yo

private: int fuelType; double gallons; public: Tank() ; -Tank ( );

Ha

Programming Challenges

1. Employee and ProductionWorker Classes Design a class named Employee. The class should keep the follow ing informa tion in

member variables: Product.ion_

Classes Problem

Worker

• •

Employee name Employee number

Hire date

ad

Solving the Employee and

m

Write one or more constructors and the appropriate accessor and mutator functions for the class.

M

uh a

m

Next, write a class named ProductionWorker that is derived from the Employee class. The ProductionWorker class should have member variables to hold the following information: •

Shift (an integer)

Hourly pay rate (a double)

The workday is divided into two shifts: day and night. The shift variable will hold an integer value representing the shift that the employee works. The day shift is shift 1 and the night shift is shift 2. Write one or more constructors and the appropriate accessor and mutator functions for the class. Demonstrate the classes by writing a program that uses a ProduetionWorker object.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

us uf

i

2. ShiftSupervisor Class

961

Yo

In a pa rticulat factory a shift superviso r is a sa laried employee who supervi ses a sh ift. In addition to a salary, the shift supervisor earns a yearly bonus when his or her shi h meets production goals. Design a ShiftSupervisor class that is de rived from the Emp l oyee class you created in Programming Cha llenge 1. The ShiftSupervisor class should have a member variable that holds the annua l sa lary and a membe r variable that holds the annual production bonus tha t a sh ih supervisor has earned. Write one or more conStruCtors and the ap propria te accessor and mutator functio ns for the cl ass. Demonstrate the class by wt iting a program that uses a ShiftSupervisor objecL

az

3. TeamLeader Class

an

Ri

In a particular factory, a team leader is an hourly paid production worker who leads a small team. In addition to hourly pay, team leaders earn a fixed monthly bonus. Team leaders are required to attend a min imum num ber of hours of training per yea r. Design a TeamLeader class that extends the ProductionWorker class you designed in Programming Challenge 1. The TeamLeader class should have member variables for the monthly bonus amount, the required number of training hours, and the number of training hours that the team leader has attended. Write one or more constructors and the appropriate accessor and mutator funct ions for the class. Demonstrate the class by writing a program rhat uses a TeamLeader object.

ss

4. Time Formal

Ha

In Program 15-17, the file Time.h contains a Time class. Design a class ca lled MilTime that is derived from the Time class. The MilTime class should convert time in military (24-hour) format to the standard time format used by the Time class. The class shou ld have the fol lowing member variables: Contains the hour in 24-hour format. For example, 1:00 pm would mil Hours: be stored as 1300 hours, and 4:30 pm woul d be stored as 1630 hou rs. Contains the seconds in standard format.

ad

milSeconds:

The class should have the following member fu nctions:

m

m

Construct or:

M

uh a

setTime:

The constructor should accept arguments for the hour and seconds, in military format. The time should then be converted w standard time and stored in the hours, min, and sec va riables of the Time class. Accepts arguments to be stored in the milHour and milSeconds variables. The time should then be converted to standard time and stored in the hours, min, and sec variables of the Time class .

getHour:

Returns the hour in military format.

getStandHr:

Returns the hour in standard forma r,

Demonstrate the class in a program that asks the user to enrer rhe time in military format. T he program should then display the rime in both military and stan dard forma t,

Input Validation: The MilTime class should not accept hours greater than 2359. less than O. It should not accept seconds greater than 59 or less than O.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

or


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 962

Chapter 15

Inheritance, Polymorphism, and Virtual Functions

i

5. Time Clock

Yo

us uf

Design a class named TimeClock. The class should be derived from the Mil Time class you designed in Programming Challenge 4. T he class should allow the programmer to pass two times to it: starting time and ending rime. The class should have a member function that returns the amount of time elapsed between the two times. For example, if the starting rime is 900 hou rs (9:00 am), and the ending rime is 1300 hou rs (1:00 pm), the elapsed time is 4 hours.

Input 'Validation: The class should not accept hours greater than 2359 or less than O.

6.

Es say class

Grammar; 30 points Spelling: 20 points Correct length: 20 points Conrent; 30 po ints

Ri

• • • •

az

Design an Essay class that is derived from the GradedActivity class presented in this chapter. The Essay class should determ ine the grade a student receives on an essay. The student's essay score can be up to 100, and is determined in the follow ing lUanner:

an

Demonstrate the class in a simple program.

7. PersonData and CustomerData classes

lastName firstName address city state

phone

• • •

zip

Ha

• •

ss

Design a class named PersonData with the following member variables:

ad

Write the appropriate accessor and mutator functions for these member variables.

m

Next, design a class named CustomerData, which is derived from the PersonData class. The Customer Data class shou ld have the follow ing me mber variables: customerNumber mailingList

m

• •

uh a

The customerNumber variable w ill be used to hold a unique integer for each customer. The mailingList variable should be a bool. It will be set to true if the customer wishes to be on a mailing list, or false if the customer does nor wish to be on a mailing list. Write appropriare accessor and mutator functions fo r these member var iables. Demonstrate an object of the CustomerData class in a simple program.

M

S. Pre f e rre dCust omer Class

A reta il store has a preferred customer plan where customers may earn discounts on all their purchases. The amount of a customer's discount is determined by the amount of the customer's cumulative purchases in the store. •

When a preferred customer spends $500, he or she gets a 5% discount on all future purchases.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 963

Review Questions and Exercises

• •

an

i

When a preferred customer spends $1,000, he or she gets a 6% discount on future purchases. When a preferred customer spends $1,500, he or she gets a 7% discoum on all future purchases. When a preferred customer spends $2,000 or more, he or she gets a 10% discoum on all future purchases.

us uf

purchasesAmount (a double) discountLevel (a double)

az

• •

Yo

Design a class named PreferredCustomer, which is derived from the CustomerData class you created in Programming Challenge 7. The PreferredCustomer class should have the following member variables:

Ri

The purchasesAmount variable holds the total of a customer's purchases to date. The discountLevel variable should be set to the correct discount percentage, according to the store's preferred customer plan. Write appropriate member functions for this class and demonstrate it in a simple program.

Input Validation: Do not accept negative values for any sales figures. 9. File Filter

ss

an

A file fi lter reads an input file, transforms it in some way, and writes the results to an output file. Write an abstract file filter class that defines a pure virtual function for transforming a character. Create one derived class of your file fi lter class that performs encryption, another rhat transforms a file to all uppercase, and another thar creates an unchanged copy of the origina l file. The class shou ld have the follow ing member function:

Ha

void doFilter(ifstream &in, of stream &out) This function should be called to perform the actual filtering. The member funct ion for transforming a single cha racter should have the prototype: char transform(char ch)

ad

The encryption class should have a constructor that takes an integer as an argument and uses it as the encryption key.

m

10. File Double-Spacer

m

Create a derived class of the abstract fi lter class of Programming Challenge 9 that double-spaces a file; that is, it inserts a blank line between any two lines of the file. 11. Course Grades

uh a

In a course, a teacher gives the following tests and assignments:

M

• • • •

A lab activity that is observed by the teacher and assigned a numeric score. A pass/fail exam that has 10 questions, The minimum passing score is 70. An es;s;ay that is assigned a numeric score. A fi nal exam that has 50 questions.

Write a class named CourseGrades. The class should have a member named grades that is an array of GradedActivity pointers. The grades array should have four elements, one for each of the assignments previously described. The class should have the following member functions:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

964

Inheritance, Polymorphism, and Virtual Functions

This function should accept the address of a GradedActivity object as its argument. This object should already hold the student's score for the lab activity. Element 0 of the grades array shou ld reference this object.

us uf

i

setLab:

setPassFailExam: This function should accept the address of a PassFailExam

Yo

object as its argument. T his ob ject should already hold the student's score for the pass/fail exam. Element 1 of the grades array should refe rence this object.

This fUllction should accept the add ress of an Essay object as irs argument. (See Programming Challenge 6 for the Essay class. If you have not completed Programming Cha llenge 6, lise a GradedActivity object instead.) This object shou ld already ho ld the student's score for the essay. Element 2 of the grades array should reference th is object.

az

setEssay:

Ri

setPassFailExam; This function should accept the address of a FinalExam object as its argument. This object should already hold the student's score for the final exam. Element 3 of the grades array should reference this object. This fu nction should display the numeric scores and grades for each clement in the grades array.

an

print:

Demonstrate the class in a program.

ss

12. Ship, Crui s eSbip, and cargoSbip Classes

• • •

Ha

Design a Ship class tha t has the following members: A member variab le for the na me of the ship (a string) A member variable for the year that the ship was built (3 string) A constructor and appropriate accessors and I!lutators A virtual print function that d isplays the ship's name and the year it was bu ilt.

A member variable for the max imum number of passengers (an int)

m

ad

Design a Cruiseship class that is derived from the Ship class. The CruiseShip class should have the following members:

A construcror and appropriate accessors and mutato rs

A print fu ncti on tha t overrides the print funct.ion in the base class. T he cruiseShip class's print func tjon should display only the ship's name and the max imum number of passengers.

m

uh a

Design a CargoShip class that is derived from t he Ship class. T he CargoShip class should have the following mem bers:

M

• • •

A member variable for the cargo capacity in tonnage (a n int ). A constructor and approp riate accessors and mutators. A print function that overrides the print funct ion in the base class. The CargoShip class's pr int function should display only the ship' s name and th e ship's cargo capac ity . .

Demonstrate the classes in a program that has an array of Ship po inters . T he array elements sho uld be initialized with the addresses of dynamically alloca ted Ship,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

96S

us uf

i

CruiseShip, and CargoShip objects. (See Program 15~ 13, Ijnes 17 through 22, for an example of how to do this. ) The program shou ld then step through the array, calling each object's print function. 1.3c. Pure Abs\ract Bast C lass Project

Define a pure abstract base class ca lled BasicShape. The Baaicshape class should Private Member Variable: area, a double used to hold the shape's area.

Yo

have the following members:

az

Public Member Functions: getArea. This function should rerum the value in the member variable area .

Ri

calcArea. This function should be a pure virrua l function. Next, define a class named Circle. It should be derived from the Basicshape class. It shou ld have the fo llowing members:

an

Private Member Variables: centerX, a long integer used to hold the x coordinate of the circle's center.

ss

centerY, a long integer used to hold the y coordinate of the circle's center. radius, a double used to hold the circle's radius.

Ha

Public Member Functions:

constructor-accepts values for centerX, centerY, and radius. Should call the overridden calcArea function described below.

ad

getCenterx-returns the value in centerX. getCenterY-rerurns the value in centerY.

m

calcArea---calculates the area ofthe circle (area =3. 14159 . . radius . . radius) and stores the resu lt in the inherited member area.

m

Next, define a class named Rectangle. Ir should be derived from the BasicShape class. I[ should have [he following members:

uh a

Private Member Variab les: width, a long integer used to hold the width of the rectangle. length, a long integer used to hold the length of the rectangle.

M

Public Member Functions: constructor-accepts va lu es for width and length. Should call the overridden calCArea function described below.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 15

966

lnheritance, Polymorphism, and Virtual Functions

the value in width.

getLength- returns the value in length.

calCArea-calculates the area of the rectangle (area the rcsulr in the inherited member area.

= length

us uf

i

get'Width-returns

" w idth) and stores

After you have created these classes, create a driver program that defines a Circle

Yo

object and a Rectangle object. Demonstrate that each object properly calculates and

reports its area.

Group Project

az

14. Bank Accounts

This program should be designed and w ritten by a team of studenrs. H ere are some suggestions: One o r more students may work on a single class.

The requ irements of the program should be analyzed so each student is given

Ri

about the same work load.

The parameters and rerurn types of each function and class member function should be decided in advance. T he program will be best impl emented as a multi-file program.

an

• •

ss

Desi gn a generic class to hold the follow ing information about a bank accou nt: Balance

Ha

Number of deposits rhis month N umbe r of withdrawals

Annual interest rate

Monthly service charges

ad

The class should have the following member functions : Accepts arguments for the balance and annual intereST rate.

deposit:

A virtual function that accepts an argument for the amount of the

m

m

constructor:

uh a

withdraw:

M

calcln t:

deposit. The function should add the argument to the account ba lance. It should also increment the variable hold ing the number of deposiTS. A

virtual function that accepts an argument for the amount of the

withdrawal. The functi on should subtract the argument from the bala nce . It should also increment the variable holding the number of

withdrawals.

A virtual function that updates rhe balance by calculating the

monthly interest earned by the account, and adding this imerest to the balance. This is performed by the following formulas: Month ly Interest Rare = (Annual Interest Rate J 12) Monthly Inreresr = Babnce ... Monthly Interest Rate Ba lance = Balan ce + Monthly Interest

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

A virtual function that subtracts the monthly service charges from

us uf

monthlyproc:

967

the balance, calls the calclnt function, and then sets the variables

that hold the number of withdrawals, number of deposits, and monthly service charges to zero.

status (to represent an active or inactive account)

Yo

Next. design a savings account class, derived from the generic account class. The savings account class shou ld have the followlng add itional member:

az

If the balance of a savings account falls below $25, it becomes inactive. (The status member could be a flag variable.) No more withdrawa ls may be made until the balance is raised above $25, at which time rhe account becomes active again. The savings account class should have the following member functions: A function that checks [0 see if the account is inactive before a withdrawal is made. (No withdrawal wi ll be allowed if the account is not active.) A withdrawal is then made by calling the base class version of the function.

deposit:

A function that checks to see if the account is inactive before a deposit is made. If the account is inactive and the deposit brings the balance above $25, the account becomes active again. The deposit is then made by calling the base class version of the function.

monthlyProc!

Before the base class function is called, this function checks the num-

an

Ri

withdraw:

Ha

ss

ber of withdrawals. If the number of withdrawals for the month is more than 4, a service charge of $1 for each withdrawal above 4 is added to the base class variable that holds the monthly service charges. (Don't forget to check the account balance after the service charge is taken. If the balallce falls below $25, the account becomes inactive.) Next, design a checking account class, also derived from the generic account class. It should have the follow ing member functions: Before the base class function is called, this function will determine if a withdrawal (a check written) will cause the balance to go below $0. U the balance goes below $0, a service charge of $15 will be taken from the account. (The withdrawa l will not be made.) If there isn't enough in the account [0 pay the service charge, the balance will become negative and the customer will owe the negative amOunt to the bank. Before the base class function is ca lled, this funcrion adds the monthly fee of $5 pillS $0.10 per withdrawal (check written) to the base class variable thar holds [he monthly service charges.

m

ad

wi thdraw:

uh a

m

monthlyProc:

M

Write a complete program that demonstrates these classes by asking the user to enter the amounts of deposits and withdrawals for a savings account and checking account. The program should display statistics for the month, including beginning balance, total amount of deposits, total amount of withdrawals, service c harges, and ending ba lance.

o

NOTE : You ma y need to add more member va riables and functions to the classes than those listed above.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 968

Chapter 15

Inheritance, Polymorphism, and Virtual Functions

us uf

i

Serendipity Booksellers Software Development ProJectPart 15: A Prob'em-So'ving Exercbe 1. Break the BookData Class inca Two Classes

Yo

Currently the BookData dass contains an of the data about n book in the store\s inventory. Now you will break the class into two classes: one that is a base class containing on genera l data about a book, and another that is a derived class contain ing data abour a book in inventory.

az

First, simplify the BookData class so it contains only the general data abour a book. Specifica ll y, modify the BookOatB class so it contains: only the fo llowing member variables and member fu nctions:

Member Variables bookTitle

Ri

isbn author

publisher

an

Member Functions setTitle setISBN

setAuthor setPub

Ha

ss

Next you will create a new class named InventoryBook. This class will be derived from the BookData class, and will hold invemory-relared data about a book. Specifically, this class w ill contain the following member variables and member functions, 'Which we r e reITlovcd ffOITl the o riginal aookData class:

Member Variables dateAdded qtyOnHand

ad

wholesale retail

m

Member FmJctions

uh a

m

setDateAdded setQty setWholesale setRetail iSE;mpty removeBook

M

2. Create the SoldBook Class Create a class named SoldBook, w h ich is derived from the InventoryBook class. Its purpose is to represent a book tha t has been sold to a customer, and perform the necessary calcula ti ons for the sa le of a book. It should have the following members:

Member Variables; taxRate

A static private member, used to hold the sa les tax rate.

qtySo l d

The quantity of this particular book that is being purchased.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Review Questions and Exercises

The sales tax on the purchase of this particular book, calculated as qtySold times retail times taxRate. (retail is inherited from InventoryBook. )

subtotal

The subtotal of the sale of this particular tirie. The subtotal is calcu-

total

lated as retail times qtySold plus tax. A private static member, used to hold the tota l of an entire sale.

Yo

us uf

tax

You should determine the accessors, mutators, and other member functions needed in this class.

M

uh a

m

m

ad

Ha

ss

an

Ri

az

The cashier function should ask the user how many titles the customer is purchasing. It should then dynamically allocate an array of SoldBook objects large enough for that many tides. The function will use the array of SoldBook objects to compute the necessary information for a customer's sale. The function will then display the simulated sa les slip on the screen.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh am

m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Yo

1

1

o

Exceptions Function Templates , 6.3 Focus on Software Engineering: Where to Start When Defining Templates

16.4 Class Templates 16.5

Introduction to the Standard Template l ibrary (STL)

ss

an

16.1 , 6.2

Ri

az

o

Ha

Exceptions

CONCEPT: Exceptions are used

[0

signa l errors or unexpected events that occur

ad

while a program is running.

m

Error testing is usually a straightforward process involving if stateme nts or other control mechanisms. For examp le, the following code segment will trap a division-by-zero error before it occurs:

if (denominator

m

cout ÂŤ

;~

0)

"ERROR : Cannot divide by zero. \ 0";

else

quotient

=

numerator / denominator;

uh a

But what if similar code is pan of a function that returns the quotient, as in the following

M

example?

971

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 972

i

Chapter 16 Exceptions, Templates, and the Standard Template library (STL)

us uf

II An unreliable division function double divide(int numerator, iot denominator) {

if (denominator : : 0) (

cout ÂŤ "ERROR: Cannot divide by zero.\n"; return 0;

Yo

)

else

return static_cast<double> (numerator) / denominatori )

az

Functions common ly signa l error conditions by returning a predetermined value. Apparenrly, the funct ion in th is example returns 0 when div ision by zero ha s been attempted. This is un rel iable, however, because 0 is a valid result of a division operation. Even though

Ri

the function displays an error message, the part of the progra m that calls the fu nction will nOt know when an error has occurred. Problems like these require sophistica ted error han-

dling techniques.

Throwing an Exception

ss

an

One way of handl ing complex error conditions is with exceptions. An exception is a value or a n object that signals an error. When the error occurs, an exception is " thrown ." For example, the following code shows the divide function, modified to throw an exception when division by zero has been attempted.

doubl e divide(int numerator, int denominator)

Ha

{

if (denominator == 0) throw ~ERROR : Cannot divide by zero. \n" ; else return static_cast<double>(numerator) I denominator;

Throwing an Exception )

ad

The following statement causes the exception to

be thrown.

throw "ERROR: Cannot divide by 2ero. \n" :

m

m

The t hrow key word is followed by an argument, which can be any va lue. As you will see, the value of the argument is used to determine the nature of the error. The function above simp ly throws a string containing an error message.

M

uh a

The line containing a throw statement is known as the throw point. When a throw statement is executed, comeol is passed to another parr of the program known as an exception handler. When an exceprion is rhrown by a function, rhe function aborts.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 973

1'\.11'1\11\\119 bll E:x.~ept.\on

us uf

i

16.1 Exceptions

To hand le an exception, a program must have a trylcatch construct. The general format o f the try/catch construct is:

try \

Yo

II code here calls functions or object member II functions tha t might thro~ an except ion. )

catch(Except ionParameter) (

II code here handles the exception

az

)

II Repeat as many catch blocks as needed .

Ri

an

Handling an Excepfion

The first part of the constrUCt is the try block. This starts with the key word try and is followed by a block of code executing any statements that might directly or indirectly cause an exception ro be thrown. The try block is immediately followed by one or more catch blocks, w hich are [he exception handl ers. A catch block starts with the key word catch, followed by a set of parentheses containing the definition of an exception pa[,ameter. For example. here is a rrylcarch construct that can be used with the divide function : try

ss

(

)

catch (char (

cout « )

endl ;

Ha

quotient - divide( numl, num2); cout « "The quotient i s " « quotient « ~exceptionString)

exceptionStr i ng;

m

m

ad

Because the divide functio n throws an exception whose va lue is a strmg) there must be an exception handlcr that catches a srring. The catch block shown catches the error message in the exceptionString paramcter, and then displays it with couto Now let's look at an entire p rogram to see how throw, try, and catch work together. In the first sample run of Progr:llTI 16-1, val id data arc given . T his shows how the program should run with no errors . In the second sample running) a denominator of 0 is given. This shows the result of the exception being thrown.

Program 16- 1

II This program demonstrates an exception being thrown and caught . 'include <iostream> using namespace std;

uh a

1 2 3

4

M

5 6 7

II Function prototype double divide{int, int) ; (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Exceptions, Templates, and the Standard Template Library (STl)

Program 16-1 8

int main()

9

{

i

Chapter 16

(continued)

int numl, num2; 1/ To hold two numbers double quotient; /1 To hold the quotient of the numbers

10

11

12

II Get two numbers. cout. « "Enter two numbers: "; cin » num! » num2j

15 16

18 19 20

try

(

quotient = divide(numl, num2)j cout « "The quotient is " « quotient «

23 24

) catch (char *exceptionStringj

25

(

27

)

29

cout «

30

return 0 ;

2.

"End of the p rogram. \0" i

)

ss

31

exceptionString;

an

cout «

26

1/* **** ******************** * ****************** * *

36

II function throws an exception.

*

37 38

//**************~*** * *************************

39

double divide(int numerator , int denominator)

40

{

41

ad

Ha

3S

II The divide function divides numerator by II denominator. If denominator is zero, the

34

if (denomi nator == 0) throw "ERROR: Cilnnot divide by zero. \n";

42 43 )

m

return static_cast<double>(numerator) I denominator;

44 45

endl;

Ri

21 22

az

/1 Divide nurn! by num2 and catch any II potential e xceptions.

17

32 33

Yo

13 14

us uf

9 74

m

Program Output with Example Input Shown In Bold

uh a

Enter two number s : 122 (Enter] The quotient is 6 End of the program .

M

Program Output with Different Example Input Shown in Bold Ente r two numbers : 120 [Enter] ERROR : Cannot divide by zero . End of the program.

As you can see from the second output screen .. the excepcion caused the program to jump out of the divide function an d into the catch block. After the ca tch block has finished, the program resumes with the first sta tement after the try/catch construct. This is illus+ trated in Figure 16-1.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 16.1 Exceptions

us uf

i

Figure 16-1 If this statement \:.l:Y throws an exception ... ____{....~ .. quotient divide(numl , num2 ); _ _ _ ~__ cout « "The quotient is " « quotient «

=

S\1:1\emen\

)

is skipped.

catch (char *exceptionString)

If the exception is a string, the program jumps to this catch clause. After the catch block is

finished. the program

/{

cout «

_ _~~.

resumes here.

exceptionStringi

) cout

«

endl;

Yo

\n\~

"End of the program. \n ";

return 0;

az

... \ll\:!ln

975

Ri

In the first output screen the user entered nonnegative val ues. No exception was thrown in the try block, so the program skipped the catch block and jumped to the statement immed iately following the try/catch construct, wh ich is in line 29. T his is illustrated in Figu re 16-2.

an

figu re 16-2 try

ss

{

quotient = divide(numl , num2); cout « "The quotient is " « quotient «

Ha

)

endl i

catch (char wexceptionString)

If no exception is thrown in the try block, the program jumps to the statement that immediately follows the try/catch construct.

{

cout «

cout «

ad

exceptionStringi

)

"End of the program.\n" ;

r e turn 0;

m

What if an Exception Is Not Caught?

uh a

m

There are fWO possible ways for a thrown exception w go uncaught. The first possibility is for the try/catch construct to contain no catch blocks with an exception parameter of the right data type. The second possibility is fo r the exception to be thrown from outside a try block. In either case, the exception will cause the enrire program to abort execution.

M

Object-Oriented Exception Handling with Classes

Now that you have an idea of how the exception mechanism in C++ works, we will exami ne an obiect-oriemed approach to exception handling. Recall the Rectangle class that was introduced in Chapte r 13. That class had the mutator funcrio ns setw.idth and setLength foe setti ng the rectangle's width and length. If a negative value was passed to either of these functions, thc class displayed an error mcssage and aborted the program. The following code shows an improved version of the Rectangle class. This version throws an exception

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 976

Chapter 16 Exceptions, Templates, and the Standa rd Template library (S rl)

Contents of Re ctangl e. h (Version 1) 1/ Specification file for the Rectangle class 'ifndef RECTANGLE H

3 4

'define RECTANGLE H

5

clas s Rectangle

6 7 8

{

Yo

1 2

private :

10 11 12 13

II The rectangle's width II The rectangle's length

az

double width: double lengt h; public :

9

1/ Empty class declaration

);

14

15

II De fault constructor

l6

Recta ngle { ) { width -

18

0.0; }

II Mutator f unctions , de f ined in Re ctangle . cpp void setWidth(double) ; vo i d setLeng t h(doub l e) ;

19

20

ss

21 22

23

II Accessor f unctions double getWidth () c onst { return width ; }

Ha

24 25

2.

double getLength() canst { ret urn l e ngt h; }

27

28 29 30

ad

double getArea() Canst { return width * length ; }

31

}; iendif

m

32 33

0 . 0 ; length -

an

17

Ri

II Exception class class NegativeSize {

us uf

i

when a negative value is passed to setWidth or set Length . (These files are stored in the Student Source Code Folder Chapter 16\Rectangle Version 1.)

Notice t he empty class declara t ion that appears in the p u blic section, in lines 12 and 13. The

uh a

m

Negative Size class has no members . The o nly im portant part of the class is its name, which will be used in the exception-handling code. Now look at the Rectangle . c pp file, where the setWidth and setLength member fu nctio ns are defined.

Contents of Recta ngl e. c pp (Version 1) 1 2

3

M

4

II Imp l ementation file for the Rectangle class .

'include "Rectangle . h"

jj ********** ********* *** *** ** ** ** *** ***** * **** ***** *** *** ** **

*

5

II setWidth sets the value of t he member vari able width.

6 7

11 * ** ** * ****-*********** *** ** ********* ***** *** *******. * * * * * * *

8

void Rectangle :: setWidt h(double w)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 16.1 Exceptions

9 (

10

us uf

i

977

if (w >; 0) width '" wi else throw NegativeSize()i

II

12

13 14

15

1/·······*··········***·*···*·····*·*·**······*·**···· .. 18 /1··· ••••• ·•· ••••••••• ·••••••••••••*••••••••••• * •• • ••• ••••••• {

if (len >- 0) length = len; else throw NegativeSize();

24 25 26

Yo

void Rectangle::setLe ngth(double len)

az

19 20 21 22 23

* •••• II setLength sets the value of the member variable length. *

Ri

16 17

}

throw NegativeSize();

an

In the set Width function, the parameter w is tested by the i f sta tement in line 10. If w is greater than or equal to 0, its val ue is assigned to the width member variable . If w holds a negative number, however, the statement in line 13 is executed:

ss

The throw statement's argument, NegativeSize ( ), ca uses an instance of the NegativeSize class to be created and thrown as an exception.

Ha

T he same series o f eveors takes place in the setLength function. If the value in the len parameter is greater than or equal to 0, irs value is assigned to the length member variable. If len holds a negative number, an instance of the NegativeSize class is thrown as a n exception in line 25.

m

1/ This program demonstrates Rectangle class exceptions. 'i nclude <iostream> 'include "Rectangle . h" using names pace std i

uh a

1 2 3 4

m

ad

ThiS way of reponing errors is much morc graceful than simply aborting the program. Any code that uses the Rectangle class must simply have a catch block to ha nd le the NegativeSize exceptions that the Rectangle class might throw. Progra m 16-2 shows an cx<unp!c. (T hi .. hie ia 3toted in the Studcnt Source Codc ['olde.l C!Jd.tJL~l. 10\ Rectangle Version 1.)

5

6

int main()

7

{

e 9

double wi dth; double length;

M

10

11 12

II Create a Rectangle object. Rectangle myRectanglei

13

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Exceptions, Templates, and the Standard Template Library (STl)

ProgrDm \6-2

i

Chapter 16

us uf

(continued)

17

II Get the wi.deh dad lengtl! . cout « "Enter the rectangle's width : " ; cin » width; cout « "Enter the rectangle's length: ";

18

cin »

2D 21 22

1/ St ore these values in the Rectangle object.

14 15 16

I.

length;

try myRectangle . setWidth(widthj; myRectangle.setLength(length);

25 26

cout « "The area of the rectangle is « myRectangle.getArea() « endli

27

)

28 29

catch (Rectangle : :NegativeSize ) {

cout «

30 31 32 J3

"Error: A negative value was entered. \n";

)

cout «

"End of the program . \n";

return 0 ;

an

3' 35

Ri

24

az

{

23

Yo

978

)

ss

Program Output with Example Input Shown In Bold Enter the rectangle s width: 10 [Enter] I

Ha

Enter the rectangle's length: 20 [Enter] The area of the rectangle is 200

End of the program.

Program Output with Different Example Input Shown In Bold Enter the rectangle's width: 5 (Enter] Enter the rectangle s length! - 5 [Enter) I

End of the program,

ad

Error: A negative value was entered .

m

m

The catch sta tement in line 28 catches the NegativeS iz e exception when it is thrown by any of the sta tements in the try block, Inside the catch statement's parentheses is the name of the NegativeSize class. Because the NegativeSize class is declared inside the Rectangle class, we have to fully qua lify the class name with the scope resolution operator. Notice that we did not define a parameter of the NegativeSize class in the cat ch statement.

uh a

In this case the catch statement only needs to specify the type of exception it handles,

M

Multiple Exceptions

The programs we have studied so far test only for a single type of error and throw on ly a single type of exception. In many cases a program will need to test for seve ral different types of errors, and signal which one has occurred, c++ allows you to throw and catch multiple exceptions. The only requirement is that each different exception be of a different type. You then code a separa te catch block fo r each type of exception that may be thrown in the try block.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 979

i

16.1 Exceptions

us uf

For example, suppose we wish to expand the Rectangle class so it throws one type of exception when a negative value is specified for the widt h, and another type of exception when a negative value is specified for the length. First, we declarc two different exception classes, such as:

{

};

II Exception class for a negative length class NegativeLength };

{

Yo

II Exception class for a negative width class NegativeWidth

Ri

az

An instance of Negativewidth will be thrown when a nega tive value is specified for the width, an d an instance of NegativeLength will be thrown when a negative value is specified for the length. The code for the modified Rectangle class is shown here. (These files are stored in the Student Sou rce Code Folder Chapter 16\Rectang le version 2.)

Contents of Rect angle. h (Version 2)

// Specification file for the Rectangle class 'i fn def RECTANGLE H 'define RECTANGLE H

4

c l ass Rectangle

6

{

private: double widt h; II The rectangle's width double length; II The rectangle's length public: II Exception class for a negat ive width class NegativeWidth

Ha

7 8 9 10 11 12

ss

5

m

17 is 19

{

20

21

m

22 23

uh a

24 25 26 27

28

M

2' 3D 31

32

};

II Exception class for a negative le ngt h class NegativeLength

ad

13 14

15 16

an

1 2 3

{ };

II Default constructor Recta ngle ( ) { width - 0 . 0; length

=

0.0; }

// Mutator func tions, defined in Rectangle.cpp void setWidth(double)i void setLe ngth (double) ; 1/ Accessor functions double getWidth() const { return width; }

doub l e getLength(} const { r eturn length ; }

33

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 980

36 37

double getArea ( ) canst { r e turn width * length; ) }; 'endif

Contents of Rectangle . cpp (Version 2)

us uf

34 35

i

Chapter 16 Exceptions, Templates, and the Standard Template Library (STL)

/1 Imp lementation file for the Rectangle class . 'inc l ude "Rectang!e.h "

5

II setWidth sets the value of the member variable width.

Yo

1 2 3

4 11------·_········_·· •••••• ·.··_.····.· •• •••••• ··· •••• ••••••• void Rectangle :: setWidth(double w) {

if (w >= 0) width = wi else throw NegativeWi dth():

11 12 13

Ri

9 10

az

7

8

*

}

16

1/···· •••••• ****··· ****** •• • •••••

17

II setLength sets the value of the member variable length.

18

11 •••• ·.·.·._·._-_ •• • •••••••••• ·. ·_···· .· __ • ••••• • •••• ••• __ ••

26

ss

21 22 23 24 25

·.***·*··**.· •••• *···k ....•.

void Rectangle::se t Length(double len) { if (l en >= 0)

Ha

"20

an

14 15

length: len ; e l se

throw Negat i veLength();

)

II This program demonstrates Rectangle class exceptions . 'incl ude <iostream> hnclude "Rectangle . h" using names pace stdi

uh a

1 2 3 4

m

Program 16-3

m

ad

Notice that in the definition of the setWidth funct ion (in Rectangle.cpp) that an instance of the NegativeWidth class is thrown in line 13. In the defini tion of the setLength function an instance of the NegativeLength class is th rown in line 25. Program 16·3 demonstrates this class. (T his fil e is stored in the Studen t Source Code Folder Chapter 16\Rectangl e Version 2.)

5

6

intmain()

7

{

M

8 9 10

double width ; double length;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

16.1 Exceptions

14

II Get the width and length.

"

caut « "Enter the rectangle's width : " ; cin » width; cout « "Enter the rectangle's lengt h: " ; cin » length;

16 17 18 19 20 21

II Store these values in the Rectangle object.

try

22

Yo

II Create a Rectangle object . Rectangle myRectang le;

11

12 13

myRectangle . setWidth(widthli myRectangle , setLength(length)i

25

cout «

2' 27 28 29 30 31

«

}

catch (Rectangle ::NegativeWidth) (

cout « «

"Error: A negative value was given ., for the rectangle's width. \n" ;

)

33

catch (Rectang!e :: NegativeLength)

J4 35

(

3. 37 38 39 40

"Error: A negative value was given "for the rectangle's length . \n ";

ss

«

an

32

cout «

Ri

"The area of the rectangle is myRectangle.getArea() « endl;

az

(

23 24

)

cout « "End of the program. \n" i return 0;

Ha

41

us uf

i

981

)

m

ad

Program Output with Example Input Shown In Bold Enter the rectangle's width : 10 (Enter] Enter the rectangle's length : 20 [Enter] The area of the rectangle is 200 End of the program.

uh a

m

Program Output with Different Example Input Shown In Bold Enter the rectangle's width: -5 [Enter) Enter the rectangle's length ; 5 [Enter) Error: A negative value was given for the rectangle's width. End of the program.

M

Program Output with Different Example Input Shown in Bold Enter the rectangle'S width: 5 (Enter] Enter the rectangle's length : -5 (Enter] Error: A negative value was given for the rectangle's length. End of the prOgram.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 16

Exceptions, Templates, and the Standard Template Libra ry (STL)

i

982

Yo

us uf

The try block, in lines 2 1 through 27, contains code that can throw twO different types of exceptions. The statement in line 23 can potentially throw a NegativeWidth exception, and the statement in line 24 can potentially throw a NegativeLength exception. To handle each of these types of exception, there are twO catch statements. The statement in line 28 ca tcbes NegativeWidth exceptions, and the statement in line 33 catches NegativeLength exceptions.

When an exception is thrown by code in the try block, C++ searches the cry/catch conStruct for a catch statement that can handle the excep tion. If the construct contains a

az

catch statement that is compati ble with the exception, control of the program is passed to the catc h block. Using Exception Handlers to Recover from Errors

Program 16 ~3 demonstrates how a trylcatch construct can have severa l catch statements

Ri

in order to handle different types of exceptions. However, the program does not use the excep tion handlers to recover from any of the errors . When the user enters a negative value for either the wid th or the length, th is program st ill halts. Program 16~4 s hows a

an

bette r example of effective exception handling. It attempts to recover from the exceptions and get valid data from the user. (Thi s file is stored in the Srudent Source Code Fo lder Chapter 16\Rectangle version 2.)

1/ This program handles the Rectangle class exceptions. 'include <iostream> tinclude "Rectangle.h" using namespace std;

Ha

1 2 3 4

ss

Program 16-4

5

6

int ma i n ( )

7

{

10 11 12

13

double width; double length; hool tryAgain = true;

ad

9

II Create a Rectangle object. Rectang le myRectangle;

14

17 18 20

II Store the width in t he myRectangle object . wh ile (tryAgain)

21

(

uh a

19

1/ Get the rectangle'S width. cout ÂŤ "Enter the rectangle's width : " ; cin Âť width;

m

15 16

II Rectangle's width II Rectangle's length II Flag to reread input

m

8

22

try

23

(

myRectangle . setWidth(width) ; II If no except ion was thrown, then the /1 next statement will execute . tryAga in - f alse;

2'

M

25

26 27

28

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

983

catch (Rectangle::NegativeWidth)

29 30 31 32 33 3. 35

(

cout « "please enter a nonnegative value : " ; cin » width; )

II Get the recta ng le's length.

37 38 39 40

cout « "Enter the rectangle's length : "; cin » length;

Yo

)

36

az

II Store the l ength in the myRectangle object. tryAgain "" true ;

41

while (tryAgain)

42 43

{ (

Ri

try

"45 46

myRectangle.setLe ngth (length) ;

47 48 49 50

II If no exception was thrown, then the II next statement will execute. tryAgain

= false;

an

)

catch (Rectang l e ::NegativeLength)

51 52

(

cout « "p l ease ente..- a no nnegative v a lue : "; cin » le ngth ;

54 55 56 57 58 59 60

ss

53 )

Ha

)

II Dis pl ay the area of the rectangle.

cout « «

"The rectangle's area is myRectangle . getArea() «

retu rn 0 ;

61

endI ;

}

ad

62

us uf

i

, 6.1 Exceptions

m

m

Program Output with Example Input Shown In Bold Enter the rectangle's width: - 1 [Enter] Please enter a nonnegative value : 10 [Enter] Enter the rectangle' 5 length ; -S [Enter] please enter a nonnegative value: 50 [Enter] The rec tangle 's area is 500

M

uh a

Let's look at how this program recovers from a NegativeWidth exception. In li ne 10 a bool flag variable, tryAgain, is defined and in it ialized with the value true . This variable wi ll indica te whether we need to get a value from the tlSef again . Lines 16 and 17 prompt the user to enter the rectangle's width. Then the program enters the whi le loop in lines 20 th rough 34. The loop repeats as long as tryAgain is true. inside the loop, the Rectangle class's setwidth member function is called in line 24. Th is statement is in a try block. If a Negativewidt h exception is thrown, the program will jump to the catc h statement in line 29 . In the catch block that follows, t he user is asked to enter a nonnegati ve number.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

984

E.xceptions, Templates, and the Standard Template Library (STl)

i

Chapter 16

If a nonnegative nu mber is passed

to

us uf

T he program then jumps Out of the try/catch construct. Beca use tryAgain is still true, the loop will repeat.

the setWidt h member function in line 24, no

exception wi ll be thrown . In tha t case, the statement in li ne 27 will execute, which sets

tryAgain to false. The program t hen jumps out of the try/catch construct. Because

Yo

try Again is now false, the loop wi ll not repeat.

The same strategy is used in lines 37 through 56 to get and val idate the rectangle's length.

Extracting Data from the Exception Class

az

Sometimes we might want an exception object to pass data back to the exception handler.

Ri

For examp le, suppose we would like the Rectangle cl ass not only to signal w hen a nega~ tive value has been given, but a lso to pass the val ue back. T h is can be accomplished by giving the exception class members in w hich dara can be stored . 1n our next modification of the Rectangle class, the Negati veWidth and NegativeLength classes have been expanded, each with a member variable and a constructor. Here is the code for the NegativeWidth class:

an

class NegativeWidt h (

Ha

ss

private: double value; public : NegativeWidth(double val) { value:: val; } doubl e getValue() const { return value; } } ;

ad

W hen we th row this except ion, we want to pass t he invalid value as an argument to the class's constructor. This is d one in the setWidth mem ber fu nction with t he follow ing statemen t:

m

throw Negativewidth(w) i

m

Th is throw s tatement creates an insta nce of the Negati veWidth class and passes a co py of the w va riable to the constructor. The constructor t hen stores this number in NegativeWidth's membc ( va(iable, value. T he cl ass insta nce carries t his member variable to the catch bloc k that intercepts th e exception.

uh a

In the catch block, the value is extracted with code such as catch (Rectangle :; NegativeWidth e)

M

(

cout « « «

"Error : " « e.getValue() is an invalid value for the" " rectangle' s width. \n " i

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 985

i

'6.1 Exceptions

us uf

Notice thar the catch block defines a parameter object named e. This is necessary because we want to call the class's getValue funct ion to retrieve the value that caused the exceptlon. Here is the code for the NegativeLength class; class NegativeLength

Yo

{

az

private : double value; public : NegativeLength(double val) { value == val; } double getvalue() canst { return value ; }

Ri

);

an

This class also has a member variable named value, and a constructOr that initializes the variable. When we throw this exception, we follow the sane general steps that were JUSt described for the NegativeWidt h exception. T he complete code for the revised Rectangle class is shown here. Program 16·5 demonstrates these classes. (These files are stored in the Student Source Code Folder Chapter 16\Rectangle Version 3.)

ss

Contents of Rectangle. h (Version 3)

II Specification file for the Rectangle class tifndef RECTANGLE H

.3

*d..:£ino:.- l'tE:CTANGL'I!:_H

5

class Rectangle { private: double width; II The rectangle's width double length; II The rectangle'S leng th public: II Exception class for a negative width class NegativeWidth

6 7

8 9

10 11 12

m

13

ad

Ha

I 2

l'

15

m

l6

,. 17

{

private: double value; public : NegativeWidth(double val) { value = val; }

uh a

"

double getValue() const { ~eturn value ; }

2D

M

21

22

);

"2.25

II Exception class for a negative length class NegativeLength

26

{

27

private: double value;

28

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Exceptions, Templates, and the Standard Template library (STL)

{ value

31 32 33

=

us uf

public : NegativeLength(double val)

29 30

val; }

double getValue() canst { return value; }

3' 35

} ;

36

37

II Default constructor

38 39

Rectangle ( )

{ width

= 0.0;

length

= 0.0;

}

40

az

/1 Mutator functions, defined in Rectangle . cpp void setWidth(double);

41

42 43

void setLength(double);

II Accessor functions double getWidth() const { return width; }

45

46 47 48

double getLength() const { return length; }

49

an

50 51

Ri

44

double getArea() canst { return width * length, }

52 53 } ;

ss

54 55

Yo

Chapter 16

986

'endif

1 2

Ha

Conten ts of Rectangl e. c pp (Version 3) 1/ Implementation file for the Rectangle class. iinclude ~Rectangle.h"

3

5

6

* //***************************************************** ••••••

II setWidth sets the value of the member variable width.

7

ad

void Rectangle : :setWidth(double w)

9

{

m

8

if (w>'" 0) width'" Wi

m

10 11 12 13

else throw NegativeWidth{w) ;

}

15 16 17

;;.**************.******************************************* II setLength sets the value of the member variable length . *

uh a

14

18

11···*·***************·*·**.**··* ••• *.*******.* ••••• *. *.* •• *.

M

19

20

void

21

{

22 23 24

len)

if (len >= 0) length len; else

=

25 26

Rectangle ~~ setLength(double

throw NegativeLength(len); }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

987

Program 16-5

4 5 6 7 8 9

II This prog r am demonstrates Rectangle class exceptions.

'include <iostream> hnclude "Rectangle . h" using namespace std; intrnain{)

Yo

1 2 :)

double wi dth; double length; II Create a Rectangle object . Rectangle myRectangle:

11

13

II Get the width and length. cout « "Enter the rectang l e's width: " ; cin » width; cout « "Ente r the rectangle's length : "; cin » length ;

Ri

14 15

az

10

12

16 17 18 19

II Store these values in the Rectangle object .

try {

22 23 24 25 26

an

20

21

ss

myRectangle . setWidth(width); rnyRectangle.setLength(length)i cout « "The area of the rectangle is « myRectangle.getArea() « end1; }

28

catch (Rectangle :: NegativeWidth e)

29

{

30

cout «

31

« «

Ha

27

"Error : .. « e . getValue() is an invalid va lue for the" " rectangle's wi dth.\n";

}

34

catch (Rectangle : :NegativeLength e)

35

{

cout. «

36 37

38

39

m

}

40

"Error: " « e.get.Value( l is an invalid value for the " " rectangle's length . \0" i

m

« «

ad

32 33

cout « "End of the program , \n" : return 0;

41

42 }

uh a

43

us uf

i

16.1 Exceptions

Program Output with Example Input Shown In Bold Enter the rectangle's width: -1 [Enter]

M

Enter the rectangle ' s l ength : 10 [Enter] Error: -1 is an invalid value for the rectangle's width. End of the program .

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

16~ S

library (STL)

(continued)

us uf

Pro gra.m

and the Standard Template

i

Chapfer r6 txcepUons, remp(ates,

Program Output with Different Example Input Shown in Bold

Yo

Bnter the rectangle' 5 width; 5 [Enter1 Enter the rectangle's length: - 1 [Enter] Error: -1 is an invalid value for the rectangle's length . End of the program.

Unwinding the Stack

Ri

az

Once an exception has been thrown, the program cannot jump back to the throw point. The function that executes a throw statement will immediately terminate. If that function was called by another funct ion, and the exception is not caught, then the ca lling function will terminate as well. This process, known as unwinding the stack, continues for the entire chain of nested function calls, from the throw point, all the way back to the try block.

If an exception is thrown by the member function of a class object, then the class destructor is caJled. If statements in the try block or branchi ng from the cry block crea ted any

an

other objects, their destructors will be called as well.

Rethrowing an Exception try

Ha

doSomething ( ) ;

ss

It is possible for try blocks to be nested. For exampl e, look at this code segment:

}

catch(exceptionl) {

II code to handle exception 1 }

ad

catch(exception2) {

II code to handle exception 2

m

}

m

In this try block, the function doSomething is called. There are twO catch blocks, one that handles exception 1, and anorher [hat hand les exception2. If the doSomething function also has a try block, then it is nested inside the one shown.

M

uh a

With nested try blocks, it IS sometimes necessary for an inner exception handler to pass an exception to an outer exception handler. Sometimes, both an inner and an outer catch block mUSt perform operations when a particular exception is thrown. These situations require that the inner catch block rethrow the exception so the outer catch block has a chance to catch it.

A catch block can rethrow an exception with the throw; statement. For example, suppose the dosomething function (called in the throw block above) calls the doSomethingElse function, which potentially can throw exceptionl or exception3. Suppose doSomething does nOt want to handle exceptionL Instead, it wants [0 rerhrow it to the outer block. The foll owing code segment illustrates how this is done:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

16. J Exceptions

us uf

try {

doSomethingElse();

} catch(Qxcept1on l) {

Yo

throw; II Rathrow the exce ption }

catch(exception3)

j

{

II Code to handle exception 3

az

}

When the first catch block catches exceptionl, the throw; Statemem simply throws the exception aga in. The 路catch block in the ollter try!catch constr uct wil l then handle the

;

Ri

exception.

Handling the bad_ alloc Exception

an

Recall from Chapter 9 tha t when the new operator fails to allocare memory, an exception is thrown. Now that you've seen how to handle exceptions, you can write code [hat determines whether the new operator was successful.

Ha

hnc lude <new>

ss

When the new operator fails to al loca te memory, c++ throws a bad alloe exception. The bad_alloe exception type is defi ned in the new header file, so any program that attempts ro catch this exception should have the fo llowing directive:

T he bad_alloc exception is in the std namespace, so be sure to have the using namespace std ; sta teme nt in your code as well.

try {

ad

Here is the genera l format of a try/catch construct that catches the bad alloc exception:

II Code that uses the new operator

m

}

catch

m

{

II Code that responds to the error

)

uh a

Program 16-6 shows an example. The program uses the new operator ro allocate a 10,000element array of doubles. If the new operator fa ils, an error message is displayed.

Program 16-6

M

1 2

J

4

II This program demonstrates the bad alloc exception.

'include <iostream> finclude <new> II Needed for bad alloc using names pace std;

5

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

989


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 16

Exceptions, Templates, and the Standard Template Library (STL)

(continued)

Program 16-6 6

int.. mainl)

7

{

8

us uf

i

990

II Pointer to double

double *ptr;

10

try

11 12

{ ptr

13 14 lS

Yo

9

new double [10000];

~

catch ( bad_ alloc) {

17 1B 19 20

"Insufficient memory.\n";

az

coutÂŤ

16

return 0 ;

Checkpoint

What is the difference between a try block and a catch block?

16.2

What happens if an exception is thrown, but not caught?

16.3

If multiple exceptions can be thrown , how does the catch block know which exception to catch?

16.4

After the catch block has handled the exception, where docs program execution

an

16.1

ss

~

Ri

}

Ha

resume?

16.5

H ow ca n an exception pass data back ro the excepti o n ha nd ler ?

ad

Function Templates

m

m

CONCEPT: A fun ction templ ate is a "generic" function that can work with any da ta type. The programmer writes the specifi cations o f tbe fun cti on, but substitutes parameters for data types . When the compiler encounters a call to the fun ction, it generates code to handle the specific data type(s ) used in th e call.

uh a

Introduction

M

Overloaded ftmctions make programm ing conveniem because only one fun ction name must be remembered for a set of func t ions that perform similar opera tions. Each of the functions, however, must still be written individually, even if they perform the same operation. For example, suppose a program uses the following overloaded squa r e functions. in t square(int number) {

return number â&#x20AC;˘ number ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

991

i

, 6.2 Function Templates

us uf

double square(double number) (

return number * number; )

Yo

The on ly differences between these twO functions are the data types of their return va lues and their parameters. In situations like this, it is ma rc convenient to write a {unction tem~ plate than an overloaded function. Function templates allow you to write a single fW1cr ion definition that works with many different data types, instead of havi ng to write a separate fun ction for each data type used.

Ri

az

A function template is not an actual fu nction, but a "mold" the compiler uses to genera te one or more fu nctions. When writing a fu nction template, yOli do not have to specify actual types for the parameters, return value, or local varia bles. Instead, you use a type parameter to specify a generic data type. When the compiler encounters a call to the function, it exam ines the data types of its arguments and gene ra tes the function code that will work with those data types. (T he generated code is known as a template function.) H ere is a function template for the square fu nction : template <class T> T square{T number)

W{iting a Function Template

an

(

return number * number; )

Ha

ss

T he beginning of a function template is marked by a template prefix, which begins with the key word template . Next is a set of angled brackets that contains one or more generic data types used in the template. A generic data type starts w ith the key word class followed by a parameter na me that stands for the data type. The exa mple JUSt given only uses one, which is named T. (If there were more, they would be separa ted by commas.) After this, the functio n definition is written as usual, except the type parameters are substituted fo r the actual data type names. In the example the fun ction header reads

ad

T square(T number) is the type para meter, or generic data type. T he header defines square as a fun ction that returns a value of type T and uses a parameter, number, which is also of type T. As men tioned before, the compiler examines each ca ll to square and fills in the appropriate data type for T. For exa mple, the following call uses an int argument;

m

T

=

m

int y, x 4; Y = square(x);

uh a

T his code will cause the compiler to generate the fu nction int square(int number) (

return number * number;

M

)

while the following sta tements double y, f = 6.2

Y = square(f);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 16 Exceptions, Templates, and the Standard Template Library (STl)

992

us uf

will generate rhe function double square(douhle number) {

return number * number ;

Program 16-7 demonstrates how this function template is used. Program 16-7

1/ Th is program uses a function template . 'include <iostream> 'include <iomanip> using names pace std j

4

az

1 2 3 5

6

II Template definition for square function. template <class T> T square(T number) {

Ri

7 8 9 10 11

Yo

)

return number * number: )

15 16 17 18

double userOoublei

II To hold int eger input II To hold double input

ss

iot main ( ) { lot userlnt;

an

12

13 14

cout « setprecision(5) ; cout « "Enter an integer and a f loa ting -point va l ue : " ; cin » userlnt » llserDouble; cout « "Here are their squares : " ; cout « square (userlnt) « " and " « square(uSerDouble) « endl; return OJ

Ha

19

20 21 22

ad

23 24 2S

Program Out put w ith Example Input Shown In Bold

~

m

m

Enter an i nteger and a floating-point va lue : 124.2 (Enter] Here are their squares: 144 and 17.64

NOTE : All type pa rameters defined in a func tion tem plate must appea r at least once in

uh a

~ "-_r_h_'_f_u_n_'r_i_o_n_p_a_r_a_n_,e_r_e_r_li_,_r.__________________________________________________~

M

Because the compiler encountered twO calls to Square in Program 16-7, each with a different parameter type, it generated the code for twO instances of the function: one with an int parameter and i nt rerum type, the other wirh a double parameter and double return type. This is illustrated in Figure 16-3. Notice in Program 16-7 that the template appea rs before al l ca ll s to square. As with regular functions, the compiler must already know the template's contents when it encounters

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 16.2 Function Temp lates

us uf

i

Figure 16-J

993

Generated Function Code (Template Function) int square(int number) (

Function Template int x - 4, y; Y ~ square(x);

V

template <class T> T square (T number) (

"

return number • number ; ~

l

~

l

double square /double number)

az

double x • 12. 5, Y - square( x);

return number · number;

Yo

Function Calls

(

r eturn number ' number;

Ri

l

a ca ll to the template function. Templates, therefore, shou ld be placed near the top of the progra m o r in a header file.

an

NOTE : A fu nction [emplate is merely the specification of a fu nction and by itself does

no t cause memory to be used. An actual instance of the funct ion is created in memory when the compiler encounte rs a ca ll to the template funct ion.

ss

()

Ha

Progra m 16-8 shows another example of a funct ion templa te. The funct ion, swapVars, uses two references to type T as paramete rs. The function swaps the coments of the vari a bles referenced by the parameters. Program 16-8

II This pro gram demon s trates t he swapVars function template .

3

finclude <iostream> using name spac e std;

,

template <class T> void swapVarS( T &varl, T &var2)

5

m

,

ad

1

2

(

10 11

temp

varl; : var2; varl var2 : tempi

uh a

12

T temp;

m

8 9

13

"15

int main()

16

M

17

18 19

char firstChar, secondChar; lnt firstInt, secondlnt;

II Two chat's

II Two ints double firstOouble , secondOouble; II Two doubles

20 (p rogram continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 994

Program 16-8

i

Chapter 16 Exceptions, Templates, and the Standard Template Library (STl )

II Get and swapVars two chars cout « "E nter two characters: "; cin » firstChar » secandCharj swapVars(firstChar, secondChar)i cout « firstC har « " " « secondChar «

21 22

23 24

25

endl;

cout « "Enter two integers: cin » firstlnt » secondlnti

29

swapVars(firstl nt, secondlnt); cout « firstl nt « « secondlnt «

30 31 32

endl ;

II Ge t and swapVars two doubles cout « "Enter two floating - point numbers: cin » firstDouble » secondDouble;

33 34

35

"j

Ri

s wapVars(firstDouble, secandDouble) ; cout « firstDouble « " " « secondDouble « return 0;

36

37

38 39

"i

az

1/ Get and swapVars two iots

28

Yo

26 27

us uf

(continued)

)

endl;

ss

an

Program Output with Example Input Shown In Bold Enter two c h aracters : A B (Enter] B A Enter t wo integers : 510 (Enter] 10 5

Ha

Enter two f loati n g - point numbers : 1.29.6 [Enter] 9 . 6 1.2

Using Operators in Function Templates template shown earlier uses the * operator with the number parameter. T his works well as long as number is of a primitive data type such as int, float , etc. If a userdefined class object is passed to the square function, however, the class must contain code for an overloaded * operator. If not, the compilet will generate a function with an error. square

ad

The

m

m

Always remember that a class object passed to a function template must support all the operations the function will perform on the object. For instance, if the function performs a comparison on the object (wi th >, <, ==, or another relational operator), those operators must be overloaded by the class obiect.

M

uh a

Function Templates with Multiple Types

More than one generic type may be used in a function template. Each type must have its own para meter, as shown in Program 16-9. T his program uses a function template named larger. T his template uses twO type parameters: Tl and T2. The sizes of the function pa rameters, varl and var2, are compared and the function returns the numbe r of bytes occupied by the larger of the two. Because the function paramete rs are specified with different rypes, the functio n generated from this templare ca n accept twO argumentS of different

ty p~s.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH , 6.2 Function Templates

us uf

1

i

Program 16-9 1/ This program demonstrates a function t emplate

2 II with two type parameters . 3 'include <iostrearn> 4 5

uS Lng namespace

6 7

template <class TI, class T2> int largest{const Tl &varl, T2 &var2)

8

{

~~u;

15

int main()

16

{

18 19

int i ~ 0; char c = • ' ; float f - 0.0;

20

double d cout «

«

2S

cout «

26

«

an

21 22 23 24

~ O.O~

"Comparing an int and a double, the l argest\n" "of the two is " « largest(i, d) « " bytes . \n" ; "Comparing a char and a float, the largest\n" "of the two is " « largest(c, f) « " bytes.\n";

ss

17

Ri

)

az

if ( sizeof(varl) > sizeof(var2») return siz e of (varl ); else return sizeof(var2);

13 14

27

return 0;

Ha

28

29

Yo

9 10 11 12

995

}

Program Output

~

m

ad

Comparing an int and a double, the largest of the two is 8 bytes. Comparing a char and a float, the largest of the two is 4 bytes.

m

NOTE : Each type parameter declared in the template prefix must be used somewhere in ~L-_th_e_t_e_m_p_l_a_ te_d_e_fi_n_it_io_n_.________________________________________________--"

uh a

Overloading with Function Templates

Function remplates may be overloaded. As with regula r functions , function templates a re overloaded by having different parameter lists. For example, there are two overloaded

versions of the

sum

functio n in Program 16-10. The first version accepts rwo arguments,

M

and the second vers ion accepts three.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 16

996

Exceptions, Templates, and the Standard Template Library (STl)

1

II This program demonstrates an overloaded function template .

2

tinclude <iostream> using namespace stdi

3 4

6

T 8Um(T vall, T va12)

7

{

return vall + val2;

B }

11

template <class T>

12

T sum(T vall, T val2, T val3)

13

{

return vall + val2 + val3;

14 15

)

"

iot main()

17 18

19

az

9 10

Yo

template <class T>

Ri

5

{

double numl, num2 , num3;

II Get two values and display their sum.

22

cout «

23 24

cin »

"Enter two values:

";

sum(numl, nUffi21 «

endl:

ss

numl » num2; cout « "Their sum is " «

an

20 21

25 26 27

us uf

i

Program 16·10

29

cout «

30

return 0 ;

Ha

28

II Get three values and display their sum . cout « "Enter three values : "i cin » numl » num2 » num3 ;

"Their sum is " «

31

sum(numl, num2, num3) «

endl;

Their sum is 19.4

ad

Program Output with Example Input Shown In Bold Enter two values: 12.56.9 (Enter]

m

Enter three values : 45.7698.3210.51 (Enter] Their sum is 154 . 59

uh a

m

There are other ways to perform overload ing witb fu nction templates as well. For example, a program might contain a regular (nomemplate ) version of a functio n as weI! as a templa te version. As long as each has a different parameter list, they can coexist as overloaded func tions.

M

Focus on Software Engineering: Where to Start When Defining Templates Quite often, it is easier to convert an existing fu nct ion inro a template than to write a template from scratch . With this in mind, you should start designing a fun ct ion [em plate by

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH '6.4 Class Tem plates

i

997

us uf

writing it first as a regular function. For example, the swapVars template in Program 16-8 would have been started as something like the following: void swapVars(int &varl, i nt &var2) {

int temp:

Yo

temp'" va r l; var l va r 2; var2 temp; )

Checkpoint

Ri

~

az

Once this funcrion is properly tested and debugged, converti ng it to a template is a sirnplt: process. Fi rsr, the template <c lass T> header is added, then a1\ the references to int that must be changed arc replaced with the data type pa rameter T.

When does the compiler actually generate code fo r a function template? T he following func tion accepts an int argument and returns half of its value as a

16.6 16.7

double:

an

double half(int number) {

return number / 2 . 0:

ss

)

Write a template that will impleme nt this function to accept an argume nt of any 16.8

What must you be sure of when passing a class object to a funct ion templ ate that uses all operator, such as * or >? What is the best method for writing a functio n templace?

ad

16.9

Ha

'ype.

Class Templates

m

m

CONCEPT; Templates may also be used to create generic classes and abstract data types. Class templates allow you to create one general version of a class without havin g to duplicate code to hand le mult iple data types .

M

uh a

Recall the IntArray class from Chapter 14. By overloading the [I operator, this class allows you to implement int arrays that perform bounds checking. Bu [ suppose you would like to have a version of this class for other data rypes? Of course, you cou ld design specialized classes such as LongAr ray, FloatArray, Doubl eAr ray, and so fonh. A better solution, however, is to design a single class temp late that works with any primitive dara type. In this section, we will converr the IntArray class inco a generalized remp lare named Simpl eVector.

Decla ring a class template plate prefix,

SllCh

IS

very similar ro decla ring a function template. First, a temis placed before the class declaration. As with

as template<class T>,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 16 Exceptions, Templates, and the Standard Template library (STl)

i

996

us uf

function templates, T (or whatever identifier you choose to lise) is (l dato rype p .. ,..""",l':l; Then, throughout the class declaration, the data type paramerer is used where you wish to support any data type, Below is the SimpleVector class template declaration.

Contents of SimpleVec tor . h

template <class T> class SimpleVector

11 12 13

{ private: T *aptri

'ifndef S! MPLEVECTOR H 'define S!MPLEVECTOR H 'include <iostream>

Ri

int arraySize;

15 16

void memError( ) i void subError() ;

17

pUblic : II Default constructor SimpleVector() { aptr : 0; arraySize

ss

20 21 22 23 24 25

II To point to the allocated II Number of elements in the II Handles memory allocation II Handles subscripts out of

~

array array errors range

Oi}

// Constructor declaration SimpleVector(int)i

Ha

IS

az

'include <new> II Needed for bad_alloe exception 'include <cstdlib> II Needed for the exit function using namespace std;

14

19

Yo

1/ Simp~eVector class template

an

t

2 3 4 5 6 7 8 9 10

II Copy constructor declaration SimpleVector{const SimpleVector &);

26

27 28 29

ad

II Destructor declaration -S impleVector() ;

30 31

1/ Accessor to return the array size

m

32

int size() canst ( return arraySize; }

m

33 34 35 36 37

1/ Accessor to return a speci f ic element T getElementAt(int position):

38

M

uh a

39

40 41 42 43 44 45 46

II Overloaded [1 operator declarat ion T &operator{](const int &);

}; •• *. II Constructor for SimpleVector class . Sets the size of the * II array and allocates memory for i t. *

(/~**·*~* * *·~·*·*··*.************************·*·***··· ***

I/**··***· · ············· · ···*~*~ · ~· * ·***·*·**·*·**·*** ***** * .

47

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 999

16.4 Class Templates

50 Sl

{ ~rr~ySize

- s; memory for the array.

II

53 54 5S 56

try {

57 58 59

catch (bsd_slloc) {

60 61 62 63 64

}

mernError();

az

// Initialize the array . for (int count = 0: count < arraySize: count++) *(aptr + count) ~ 0;

Ri

67

Yo

aptr = new T tS];

65

68

5)

A~locote

52

66

us uf

templ ~tQ

Simplevector<T>::SimpleVector(int

i

<class T>

~Q

49

1/****··*··*·································

II Copy Constructor for SimpleVector class . • //*.**********.* •• ****.** ••• ****.************

template <class T> SimpleVector<T> : :SimpleVector(const SimpleVector &obj)

73

{

an

69 70 71 72

1/ Copy the array size. arraySize = obj.arraySizei

77 78

II Allocate memory for the array. aptr = new T [arraySizeJi if (aptr == 0) mernError();

Ha

ss

74 75 76

79

80 Bl 82

II Copy the elements of obj's array.

.3 84

for(~nt

86

)

1/·***······**·******··*·*··*·***·*·*·** 1/ DestrUCtor for SimpleVector class . •

m

87

ad

B5

count _ 0; count < arra ySiz e ; count++ ) ·(aptr + count) - ·(obj.aptr + count);

BB

//.* •• **********************************

91 92

template <class T> SimpleVector<T>::-SimpleVector()

93

{

M

uh a

m

89 90

94 95 96 97 98

if (arraySize > 0) delete [] aptr; }

99

II memError function. Displays an error message and

II·*·*·***·*····***···*···*······.· •••••• A•• **A*AA*A*A *** • 100 II terminates the program when memory allocation fails.

A

101

// •••••••••••• *** ••• * •••••••••••••••• * •• ***.** •• * ••••••••

102

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

cout«

"ERROR:Cannot allocate memory.\n";

exit(EXIT_FAILURE); }

// ******* ********** ******************************* ** **W*K __ ._ II subError function. Displays an error message and • II terminates the program when a subscript is out of r ange. * 1/*************************************************·*· W*K ___ _ template <class T> vo id SimpleVector<T>::subError() { cout « "ERROR: Subscript ou t of range . \n" ;

exit(EXIT_FAILURE); )

121

an

11············································***····* .** template <class T> T SimpleVector<T>::getElementAt(int sub) {

if (sub < 0 I I sub >= arraySize) subError ( ) ; return aptr[sub]i

}

••• II Overloaded [1 operator . The argument is a subscript . • II This function returns a reference to the element * II in the array indexed by the subscript. • II·***·*·······*···****·~~*~··*·*~**·~~·***·~·****+*·· ••• II·········**··***··*·*····****·**·*······*·*····~···~

m

13 0 13 1 1 32 133 13. 135 136 13 7 13B 13 9 140 1 41 14 2 1 43 14. 1 45 146 147 14. 149

ss

129

II getElementAt function. The argument is a subscript. II This function returns the value stored at the subII cript in the array.

Ha

128

//***********************************.***************** ••

ad

1 22 123 124 125 126 1 27

us uf

{

119 120

i

template <class T>

void SimpleVector<T>;:memError()

Yo

103 104 1 05 1 06 107 lOB 109 110 111 112 11 3 1 14 11 5 116 117 11B

Exceptions, Templates, and the Standard Template library (STL)

az

Chapter 16

Ri

1000

template <class T> T &SimpleVector<T> ::operator[)(const i nt &sub)

M

uh a

m

{

if (sub < 0 I I sub >- arraySize) subError ( ) i return aptr[sub] ;

'endit

N OTE : The arraySize member variabl e is d eclared as an into This is because it holds the size of the array, which will be an integer value, regardless of the data type of the array. This is also why the size member fu nction rerurns an into

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 16.4 Class Templates

us uf

i

Defining Objects of the Class Template

1001

C lass template ob jects are defined li ke objects of o rd inary classes, with one small difference: the data type you wish to pass to the type parameter must be speci6ed. Placing rhe data type name inside angled brackets immediately follow ing the class name does t h is . For example, t he following stateme nts create twO SimpleVector objects: intTable and doubleT able.

Yo

simplevector<int> intTable(lO); SimpleVector<double> doubleTable(1 0 );

In the definition of intTable, the data type lot will be used in t he temp late everyw here t he type parameter T appears. This will cause intTable to Store a n array of ints. Li ke-

az

wise, the definition of doubleTable passes the da ta type double intO t he parameter T, ca using it to St ore an array o f doubleS. T h is is demonstrated In Program 16-11.

' i nclude <iost r eam> linclude "SimpleVector.h" using oamespace std;

5

6

iot ma i n()

7 8

(

11

12 13 14 15

const lnt SIZE: 10; int count ;

II Create a SlmpleVector o f lnts. SlmpleVector<iot> intTable(SIZE);

II Create a SlmpleVector of doubles . Simpl eVector <double> doubleTab l e(SIZB);

16

17

II Number of elements II Loop counter

Ha

9 10

an

4

II This program demonstrates the SimpleVector template .

ss

1 2 3

Ri

Program 16-11

II Store values in the two Si mpleVectors. for (count: 0; count < SIZE; count ++)

19

{

25 26 27

II Display t he values in the Simpl eVectors . cout « "These values are in int Table : \n" ; f or (count ~ 0; count < SIZE ; count++) cout « intTable[count] « ,. "; cout « endl; COllt « "These v allles a r e in doubleTable : \o"; for (count = 0, count < SIZE ; cOllnt++ ) cout « doubleTable [count 1 « " "; cout « endl;

uh a

28 29 30 31 32

)

m

23 24

m

intTable[countl = (count * 2) ; doub1eTable[cou nt] = (count * 2 . 14);

20 21 22

ad

16

M

33

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 16

Exceptions, Templates, and the Standard Template library (STl )

i

(continued)

Program 16· 11

/1 Use the standard + operator on the elements. cout « "\nAdding 5 to each e lement of intTable" «

" and doubleTable. \n" ;

for (count: OJ count {

<:

SIZE : count++)

i ntTable[CQunt) = intTable[countl + 5; doubleTahle[countl ~ doubleTable(countj + 5.0:

41 42

II Display the values in the SimpleVectors. cout « "These values are in intTable : \0";

44

for (count

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

cout «

0: count < SIZE; count++) intTable[count] « ~ "j

=

cout «

i

Ri

cout « endl: cout « "These values are in doubleTable: \n" for (count = 0; count <: SIZEi count++) cout « doubleTable[cQunt] « " .oj

az

43

Yo

34 35 36 37 38 39 40

endl :

Ha

intTable[count] ++; doubleTablelcount]++;

ss

{

an

II Use the standard ++ operator on the elements. cout « "\nIncrementing each element of intTable and" « " doubleTable. \n" ; for (count = 0; count < SIZE; count+ +)

II Display the values in the SimpleVectors . cout « "These values are in intTable : \n " ; for (count - 0; count < SIZEj count++) cout « intTable[count} « " "i cout « endl; cout « "These values are in doubleTable ! \n "; for (count = 0; count < SIZE; count++) cout « doubleTable[count] « " "; cout « endl;

68 6' 70 71

m

ad

67

return 0 ;

72 )

m

73

us uf

1002

Program Output

These values are in intTable :

uh a

o 2 4 6 8 10 12 14 16 18 These values are in doubleTable:

2.14 4 . 28 6.42 8.56 10 . 7 12 . 84 14 . 98 17 . 12 19.26

M

o

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1003

i

, 6.4 Class Templates

Class Templates and Inheritance

Yo

each element of intTable and doubleTable. are in intTab1e: 16 18 20 22 24 are in doubleTable: 12 . 42 14 . 56 16 . 7 18.84 20.98 23.12 25.26

az

Incrementing These values 6 8 10 12 14 These values 68.14 10.28

us uf

Adding 5 to each element of intTable and doubleTable. These values are in intTable: 5 7 9 11 13 15 17 19 21 23 These values are in doubleTable : 5 7.14 9 . 28 11.42 13.56 15.7 17.84 19.98 22.12 24 . 26

Contents of SearchableVector . h ii fnd e f SEARCHABLEVECTOR H tde fi ne SEARCHABLEVECTOR H tinc l ude "Simp l eVector .h"

5 6

template <class T> class Searchab1eVector

7

{

8

public : II Def ault constructor Searchab1eVector(); SimpleVector<T>{ ) ()

10 11 12

Simplevector<T>(sizej

ad

{ }

II Copy constructor SearchableVector(const Sea rchableVector &);

m

19

ss

I I Constructor Searchab leVector(int size)

13 14

15 16 17 18

public Sirnp leVector<T>

Ha

9

the following tem-

an

1 2 3

,

In

Ri

Inheritance can easil y be a pplied to class templates. for example, plare, SearchableVector is derived from the S i mpleVector class.

II Acc e ssor to find an item iot findltem(const T);

20

21

m

22 23

"

uh a

25 26

1/ ******** ***** **** ************ ***** *** ** ************* ***

II

Copy constructor

11***** *********************** *** ************ ********* ** *

M

27

28 29 30 31 32

33 34

template <class T> SearchableVec tor <T> : : Searchab leVector(const SearchableVector &obj) SimpleVector<T>{obj . s i ze(») { for(int count = 0; count < this->s i z e( ); count++) this->oper ator(l(count) - obj[count]; }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

35

39

40 41 42 43

us uf

38

11·····*··**·-··_---_·_----------_·_··_·_· __ ··---_···· ***

/1 findltem function • • II Th is function searches for item . If item i s found II the subscript is returned . Otherwise -1 is returned . * 11*********** ***** ********* ** ************************* ***

template <class T> i n t SearchableVector<T> :: findltern(COnst T item)

"

{

for (int count

45 46 47

m

0 ; count <= this->size(): count++)

{

if (getElementAt(count) return count;

48

"

==

item)

)

return -1;

50 51

)

52

Jendif

Yo

36 37

i

Exceptions, Templates, and the Standard Template Library (STL)

az

Chapter 1 6

Ri

1004

an

This class remplate defines a searchable version of the SimpleVector class. The member function findltem accepts an argument, and performs a simple linear search to determine whether the argument's value is stored in the array. If the value is found in the array, its subscript is returned. Otherwise, -1 is returned.

ss

Notice that each time the name Simple Vector is used in the class template, the type parameter T is used with it. f or example, here is the first line of the class declaration, in line 6, which names SimpleVector as the base class:

Ha

class SearchableVector : public SimpleVector<T>

Also, here are the function headers fo r the class constructors: SearchableVector() : SimpleVector<T>() SearchableVector(int size) : SimpleVector<T>(size)

Because simpleVector is a class template, the type parameter must be pa ssed ro it.

m

Program 16-12

ad

Program 16-12 demonstrates the class by storing values in two SearchableVector objects and then searc hing fo r a specific val ue in each.

II This program demonstrates the SearchableVector template. ' include <iostream> 'include "SearchableVector . h"

4

using names pace std;

uh a

5

m

1 2 3

6 7

B

canst int SIZE

= 10;

II Number of elements

int count;

II Loop counter

int result;

1/ To hold search results

M

9 10 11

int ma i n() {

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH '6.4 Class Templates

us uf

II Store values in the objects . for (count E 0; count < SIZE; count++) {

I.

Yo

intTable[count] = (count * 2) ; = (count * 2 . 14);

doubleTable[countj

20 21 22 23

II Display the values in the objects. COllt « "These values are in intTable : \n"; for (count = 0; count < SIZE; count++)

25

az

}

"

cout « intTable(cQuntj « " "; coot « endl « endl; cout « "These values are in doubleTable: \n"; for (count = 0; count < SIZE; count++) cout « doubleTable [count I « " "; COllt « end!;

26

27 28

Ri

2. 30 31 32 33 3' 35 36 37 38 3. 40

II Search for the value 6 in intTable . "\nSearching for 6 in intTable. \n";

an

cout «

endl;

Ha

ss

result: intTable.findItem(6); if (result == -1) cout « "6 was not found in intTable.\n"; else cout « "6 was found at subscript ., « result «

42 43 44 45

ad

II Search for the value 12.84 in doubleTable. cout « "\nSearching for 12.84 in doubleTable. \n" ; result = doubleTable . findItem(12.84); if (result == -1) cout« "12.84 was not found in doubleTable . \n"; else cout « "12 . 84 was found at subscript" « result « return 0;

41

}

endl;

m

46 47 48 4.

i

II Create two SearchableVector objects. SearchableVector<int> intTable(SIZE); Searchablevector<double> doubleTable(SIZEJi

12 13 14 15 16 17 18

1 005

Program Output

m

These values are in intTable : o 2 4 6 8 10 12 14 16 18

uh a

These values are in doubleTable : o 2.14 4 . 28 6.42 8 . 56 10.7 12.84 14 . 98 17.12 19 . 26

Searching for 6 in intTable.

6 was found at subscript 3

M

Searching for 12 . 84 in doubleTable. 12.84 was found at subscript 6

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1006

Chapter 16

Exc.eptions, Templates, and the Standard Tem plate Library (STL)

us uf

i

T he SearchableVector class demonstrates that a class template ma y be derive,d from another class template. In add ition, class templates may be derived from ordinary ,classes, and ordinary classes may be derived from class templates.

Specialized Templates

az

Yo

Suppose you have a template thar works for all data types but one. For example, th e SimpleVector and SearchableVector classes work wei! with numeric, and even r;haracrer, data. But rhey will not work with strings. Situations like this require the use of specialized templates. A specialized temp la re is one that is designed to work wirh a spednc data type. In the decla ration, the actual data type is used instead of a type parameter. For example, the declaration of a specialized version of the SimpleVector class migpr start like this: class SimpleVector<char *>

Ri

The compiler wou ld know that this version of the simpleVector class is intended)for the char * data type. Anytime an object is defined of the type simp levec tor<cha~*>, the comp iler will use this template to genera te the code.

16.10

an

Checkpoint Suppose you r program uses a class template named List, which is defined, as template<class T> class List {

,

/ / Member s are declared here...

Ha

}

ss

~

Give an example of how you would use int as the data type in the definition , of a List o bject. (Assume the class has a defaulr constructor.) As the following Rectangle class is written, the width and length memb:ers are doubles . Rewrite the class as a template rhat will accept any data type fo~ these members.

ad

16.11

class Rec tangle

M

uh a

m

m

(

private : double width; double l ength ; pub lic : void se t Oata(double w, double 1) { width = w; length - I;} double getWidth() { return width; } doub l e getLength() { return length; } double getArea() { return width * l ength;

} ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH , 6.5 Introduction to the Standard Template library (STl)

i

1007

us uf

Introduction to the Standard Template Library (STL)

Yo

CONCEPT; The Standard Template Library contains many templates for useful algorithms and data Structures .

NOTE: Section 7.12 of Chapter 7 presents a concise introduction to the Standard Temp late Library, and discusses the vector data type. T his discussion is continued in Section 8.5 of Chapter 8. If you have not already studied those sections, do so now.

Ri

az

In addition to its runtime library, which you have used throughout this book, C++ also provides a libra ry of templates. The Standard Template Library (or STL) contains numerous generic templates for im plementing abstract data types (ADTs) and algorithms. In this section you will be in troduced to the general types of ADTs and algorithms that may be foun d in the STL.

an

Abstract Data Types

ss

The mOSt important data Structures in the STL are c.Olltainers and iterators. A container is a class that stores da ta and orga nizes it in some fashion. An iterator is an object that behaves like a poimer. It is used to access the individual data elemen ts in a container.

Ha

There are two types of container classes in the STi: sequence and associatifJe. A sequence container organizes da ta in a seq uentia l fashion similar CO an array. The three sequence containers currently provided are listed in Table 16-1. Table 16-1

Description An expandable array. Values may be added to or removed from the end or mi dd le of a vector.

deque

Like a vector, but allows val ues to be added

list

A doub ly linked list of data elements. Values may be inserted to or removed from any pos ition. (You will learn mOre about linked lists in Chapter 17.)

CO

o r removed from the front.

m

m

ad

Container Na me vector

Performance Differences Between vectors, deques, and lists

uh a

T here is a difference in performance between vectors, deques, and lists. When choosing one of these templates fO use in your program , remember the following points: •

M

• •

A vector is ca pable of qu ick ly addi ng values to its end. Insertions at orher points arc not as efficient. A deque is capable of quickly adding values co its front and its end. deques are not efficient at inserting values at other positions, however. A list is capable of quick ly inserting values anywhere in its sequence. lists do not, however, provide random access.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 16 Exceptions, Templates, and the Standard Template Library (STl)

1008

i

An associa tive container uses keys ro rapidly access elements. (If you've ever used a rela -

us uf

tional database, you are probably fam iliar with the concept o f keys.) The four ass~ciative containers currently supported are shown in Table 16-2.

Table 16路2 Description Stores a set of keys. No duplica te values are allowed.

mul tise t map

5wres a set of keys. Duplicates are allowed. Maps a set of keys to data elements. Only one key per data eleme nt is a l ~bwed . Duplicates are not allowed .

multimap

Maps a ser of keys to data elements. Ma ny keys per data element are allqwed.

Yo

Container Name set

az

Duplicates a re allowed.

Ri

Iterators are generalizations of pointers and are used to access data stored in con~ainers. The types of iterators are shown in Table 16-3. Table 16-3

Descripti o n

Fo rward

Can o nly move forward in a container (uses the ++ operator).

Bidirectional

Can move forward or backward in a container (uses the ++ and - operators ). Can move forward and backward, and ca n jump to a specific data ekment in a container. Can be used with an input stream to read data from a n input device or a file. Can be used with an output stream to write data to an ourput device or a fi le.

an

Iterato! Typc

ss

Random-access Input

Ha

Output

ad

lterators are associated with containers. T he type of container you have dererm ipes the type of iterator you use. For example, vectors a nd deques require random-acces,S iterators, while lists, sets, multisets, maps, and multimaps require bidirect ional iter'ators.

Algorithms

m

Table 16路4

m

The algorithms provided by the ST L are implemented as function templates, and perfotm various ope rations on elements of containers. T here are many algorithms in the ST L, but Table 16-4 lists a few of them. (T he tab le gives only ge neral descr iptions. )

M

uh a

Algorithm binary_ search

Description Performs a binary search fo r an obj ect a nd returns true if the object is found.

Example: bi nary search(iterl, iter2, value) ; In this statement, iterl and iter2 poine to elements in a container. (iterl points to the first element in the range and i ter2 points to the last element in the range. ) The statement performs a binary search on the range of elements~ searching for value. The binary_search func tion returns true if the element was found, and fa~ae if the element w~s nOt fo und. (table continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1009

16.5 Introduction to the Standard Template Library (STl)

i

(continued)

us uf

Table 16-4

Description Returns the number of times a value appears in a range.

fin d

Example: iter3 = count(iterl, iter2, value); In this statemen t, iterl and ite r2 point to elements in a container. (iterl points to the first element in the range and iter2 points to the last element in the ra nge.) T he statement returns the number of times value appea rs in the range of elements. Finds the first o bject in a con ta iner that matches a value and retu rns an iterator

Yo

Algorithm count

it .

az

[0

Ri

Example: iter3 = find(iter l , iter2, value); fn this statement, iterl and iter2 point to elements in a container. (iterl points to the first elemen t in the range and i ter2 points to the last element in the range.) The statement searches the range of elements for value. If value is found. the function returns an iterator to the element contai ning it. Executes a function for each element in a container. Example: for_each(iterl, iter2, func); In this sta tement, iterl and iter2 point to elements in a container. (iterl points to the fi rst element in the range and i ter2 points to the last element in the range.) The third argument. func, is [he name of a function. T he Statement calls the fu nction func for each element in the range. passi ng the element as an argument. Returns an iteratOr to the largest object in a range. Example: iter3 = max_e lement(iterl , iter2); In this statement, iterl and iter2 point to e[emenrs in a conrainer. (iterl points to the first element in the range and iter2 points to the last element;n the range. ) The statement returns an iterator ro the element containing the largest value in the range. Returns an iterator to the smallest object in a range. Example: iter3 = min_element(iterl, iter2) ; Tn this statement, iterl and iter2 point to elements in a container. (iterl points to the first element in the range and iter2 points to the last element III the ra nge.) The sta tement returns an iterator to the e1emenr containing the ~maJ[est va lue in the range.

Ha

ss

an

for each

(table continues)

M

uh a

m

min element

m

ad

max element

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 16 Exceptions, Templates. and the Standard Template library (STL)

(continued)

Algorirhm random shuffle

i

Table 16-4

us uf

1010

Description Rando ml y shuffles the elements of a conta in er.

Example: random s huffle( iter l, iter2)i In th is statement, iterl and iter2 poim to elements in a container. (iterl

Yo

points to the fi rst element in the range and i ter2 poin ts to the laSt ele me?t in t he

range.) Th t statement randomly reorders rhe elements in the range.

sort

Sorts a range of elements.

Example:

az

sort(iterl, iter2); In this sta tement, iter! and iter2 poim to elements in a container. (iter!

Ri

points to the first clement in the range and iter2 poin ts to the last eleme?t in the range.) The statement sorts the elemenrs in the range in ascending order.

Example Programs Using the STL

Now that you have been introduced to [he types of dara structures and algori thms 'offered

an

by the STL, lec's look at some simple programs thar use them.

ss

Containers

Progra m 16-13 provides a limIted demonstration of the vector class template. The, mem-

Ha

bet functions of vector used in th is program are listed in Table 16-5.

Table 16-5

Member Function Description size( ) Returns the number of elements in the vector. push_back() Accepts as an a rgument a value to be inserted into the vector. The argument is

ad

insetted after the last element. (Pushed pop_back ( )

the back of the vector.)

Removes the last element fro m the vector. Allows array-like access of existing vector elements, (The vector must alrea dy contain elements for this operator to work. It cannot be used to insert nfw va lues into the vector.)

m

m

operator [ J

OntO

The vector class template has many more member funct ions, but these are enough to

uh a

demonstrate the class.

Program 16路 13

I{ This program provides a simple demonstration of the II vector STL template . 'i nclude <iostre am> l include <vecto r > II Inc lude the vector header

5

using namespace std ;

M

1 2 3 4

,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 16.5 Introduction to the Standard Template library (STL)

i

int main () { int count;

II

us uf

7 8 9

Loop counter

10

II Define a vector object. vector<int> vect;

11 12 13 14

II II

16 17 18 19

Yo

Use the size member funct ion to get the number of elements in t he vector. cout « "vect starts with" « vect.size() « " elements . \n";

15

10 11

az

II Use push back to push values into the vector. for (count - 0 ; count < 10; count++) vect . push_back(count) j

20 21

22

II Display the size of the vector now. cout « "NOW vect has" « vect.size() « " elements . Here they are:\n";

27

II Use the [} opera t or to display each element . for (count = 0; count < vect.size(); count++) cout « vec t [count] « " " j cout « endl;

an

28 29 30

Ri

23 24 25 26

31 32

36 37

Ha

ss

II Use the pop_back member f unction . cout« ··Popping the values out of vect ... \n" i for ( count = Oi count < 10 i count++) vect.pop_ back()j

33 34 35

II Display t he size of the vector now. cout « "Now vect has " « vect. size () « return OJ

38 39 )

ad

40

are ~

m

m

Program Output vect starts with 0 elements . NOW vect has 10 elements. Here they 01234 5 6 7 8 9 Popping the values out of vect ... Now vect has 0 elements .

.. elements. \n" i

Notice the inclusion of the vector header file in line 4 , which is required for the vector co n tainer. vectors are one of the simplest types of containers in rhe STL. In fotlow ing chapters, yo u will see examples using other types of containers.

uh a

-

Storing

Obi~CI$

vecto~

M

a

in

Iterators

In

Program

16-13, the vector's elements were accessed by rhe container's member func-

tions. Irerators may also be used to access and manipulate container elements. Program 16-14 demonstrates the use of an iterator with a vector object.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 16 Exceptions, Templates, and the Standard Template library (STl )

1012

1

II Th is program provides a simple iterator demonstration .

2

linclude <iostream> li nclude <vector> II Include the vector header using names pace std;

5 6 7 8

,

int main()

Yo

3 4

{

int count ;

II Loop counter

II Define a vector object . vector<int> vect;

10 11

us uf

i

Program 16-14

az

12

II Define an iterator object . vector<int >:: iterator iter ;

13

14 15

Ri

II Use pu sh_back to push values into the vector . for (count ~ 0; count < 10 ; count++)

16 17 18

vect . push_back(count)j

19

II Step the i t erator through the vector,

21 23

II and use it to d i splay the vector ' s contents . cout « "Here are the values in vect: "; for (iter ; vect.begin() ; iter < vect.end(); iter++)

24

{

cout «

25 26 27 28 29

.. ";

{ )

34

return 0; )

·iter

«

"

";

ad

cout «

32 33

Ha

II Step t he iterator t hrough the vector backwards . cout « "'nand here they are backwards: "; f or (iter = vect .end() - I : iter >= vect .begin() : iter -- )

30 31

35

*iter «

)

ss

22

an

20

m

m

Program Output Here are the values in vect: 0 1 2 3 4 5 6 7 8 9 and here they are backwards: 9 8 7 6 5 4 3 2 1 0

uh a

The definition of an iterator is closely related to the definition of the container it is to be used with. Fo r example, Prog ram 16-14 defines a vec t or of lnts as: vector<int > vect ;

The iterator that will work with the vector is defined as:

M

vector<int> : :iterator iter;

This definition creates an iterato r specifically for a ve ctor of ints . T he compiler automatica ll y chooses the righ t type (in this case, a random-access iterator). T he second for loop in lines 23 through 26 causes the ircnltor to step throllgh each element in the vector:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1013

16.5 Introduction to the Stan dard Template Library (Sl1)

= vect.begin();

i

iter < vect . end(); iter++)

us uf

for (iter

T he loop's ini tial iza tion expression uses the container's begin{ )member function, which returns an iterato r po inting to the beginn ing of the vector. The statement iter: vect.begin()i

Yo

causes iter to point to the first elemenr in the vector. The rest expression uses the end ( ) member func tion, which retu rns a n iteraror pointing to the loca tion just past the end of the container: ite r < vect . end();

az

As long as iter points to an element prior to the end of the vector, this statement will be true. The loop's update expression uses the ++ operator to increment the iterator. This ca uses the iterator to po im to the next element in the vector.

cout «

*i t er «

to

disp lay the element that the iter-

Ri

The body of the loop lIses a cout statement in line 25 atOr points to:

" ";

an

Like a poin ter, iterarors may be dereferenced with the * operator. T he sta tement above causes the value poim ed to by iter to be displayed.

ss

Back to the ve ctor Template

Ha

Ta ble 16-6 lists severa l more member functions of the vector class template. Some of these accept irerarors as arguments and/or recurn an iterator.

Table 16-6 Member Function

m

m

back ( )

uh a

begin( )

capacity( )

M

Examples and Description Returns the value of the element located at element in the vector. Example: x = vect.at(5); Th is sta tement assigns the value of ele ment 5 of vect to x. Returns a reference to the last element in the vecwr.

ad

at(element)

Example: cout « vect.back(} « endl; Returns an iterator pointing to the vector's fi rst element. Example: iter = vect . begin(); Returns the maximum number of elements that may be stored in the vector without addit ional memory being allocated . (This is not the same value as returned by the size member func tion.)

Example: x = vect.capacity().

T his statement assigns the capacity of vect

to

x.

(tabJe continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 16

1014

Exceptions, Templates, and the Standard Template Library (STL)

Exa mples a nd Description Clea rs a vector of all its elements.

Yo

Example: vect.clear(); Th is statement removes all the elements from vect.

us uf

Member FUDClion clear( )

i

Table 16-6 (continued)

empty ( )

Returns true if the vector is empty. Otherw ise, it returns false.

az

Example: if (vect.empty()) cout « "The vector is empty ."; This sta tement displays the message jf vect is empty.

Returns an ireratOr pointing to the vector's last element.

eraser)

Example: iter ~ vect.end(); Causes the vector element pointed to by the iterator iter Exam1Jle: vect . erase(iter)i

to

be removed.

Causes all the vector elements from the iterator iterl to the itera ror iter2 to be removed.

an

erase(iterl,iter2 )

Ri

end( )

ss

Example: vect.erase(firstlter, secondlter ): Returns a reference to the vector's fi rst element.

front()

m

m

resize(n,value)

rever se ( )

uh a

endl:

Inserts a value into a vector.

Example: vect.insert(iter, 22); This statement inserts the value 22 into vect. The value is insened into the element before the one poi nted to by iter. Resizes a vector by n new elements. T he clements arc initialized with value.

ad

insert (iter, value)

Ha

Example: cout « vector.front() «

Example: vect.resize(lO , O); This statement adds ten new elements to vect and initializes the new elements with the value O. Reverses the order of the items stored in a vector. Example: vect.reverse();

M

Algorithms

There are many algorithms in the STL, implemented as function templates. Program 16-15 demonstrates random_shuffle, sort, and binary_search.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH lOIS

16.5 Introduction to the Standard Template Library (STl)

9 10

11

us uf Yo

8

int main() { int count;

I I Loop counter

II Define a vector object. vector<int> vect:

12 13 14 15

az

4 5 6 7

II A simple demonstration of STL a lgorithms linclude <ioatream> iinclude <vector> II Required for the vector type iinclude <algorithm> II Required for STL algorithms using namespace std;

II Use push back to push values into the vector. for (count - 0 : count < 10 : count++) vect.push_back(count);

16 17

18 19 20

Ri

1 2 3

i

Program 16-15

II Display the vector's e l ements . cout « "The vector has" « vect . size() « " elements. Here they are:\n"i for (count - 0; count < vect . size(); count++) cout « vect[countJ « " "; cout « endl ;

an

21 22 23

2'

II Randomly shuffle the vector's contents. random_shuffle( vec t ,begin{) , vect.end{));

ss

25

26 27 28

Ha

II Display the vector's elements. cout « "The elements have been shuffled : \n "i for (count: 0; count < vect . size(); count++) cout « vect[countJ « " ": cout « end1;

29 30 31 32

33

II Now sort the vector's e l ements. sort(vect.beg i n(), vect.end{»);

ad

34

35 36

II Display the vector's elements again . cout « "The eleme nt s have been sorted : \n"'; for (count = 0; count < vect.size() ; count++) cout « vect[count] « " "; cout « endl;

m

37

m

38 39 40 41 42

II Now search for an element with t he value 7. if (binary_search(vect.begin(), vect.end(), 7)) cout « "The value 7 was f ound in the vector. \n" : else cout « "The value 7 was not found in the vector . \n"; return 0:

uh a

43 44

45

46

47 48

M

"

)

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

us uf

Pro gram Output The vector has 10 0 1 2 3 4 5 6 7 8 T h e e l ements have 4 3 0 2 6 7 8 9 5 Th e elements have

(continued)

elements. Here they are : 9

been shuffled: 1

been sorted:

Yo

Program 16· 15

i

Chapter 16 Exceptions, Templates, and the Standard Templa te library (STl)

1016

0 1 2 3 4 5 6 7 8 9 The

value 7 was found in the vector .

az

~L-_N_O __T_E __: _T_h_ ,__s_·r_L__" _lg_O_'_;'_h_m_S__,,_q_U_;_' _,_,_h _, _a_'_'_o_r_i_t_h_m_l_,,_._d_,_,_fi_l_,_,____________________-'

Ri

T he random_shuffle functio n rea rranges the elements of a concaincr. In lin'i 26 of Program 16· 15, it is called in the following manner: I random_shuffle(vect.begin (), vect.end(»;

an

T he fu nction takes two arguments, which together represent a range of elemencs w ith in a container. The first argu ment is an iterator to the first element in the range. In tlUs case, vect . begin ( ) is used. T he second argument is an iterator to the last element in th~ range. H ere we have used vect.end(). These argu ments tell random_shuffle to rearqnge all the elements from the begi nning to the end of the vect co ntainer.

ss

T he sort algorithm also takes iterators to a range o f elements. H ere is the fu nction ca ll that appears in li ne 35:

Ha

sort (vect . begin(), vect . end(» ;

All the elements with in the range are soreed in ascending order.

ad

The bin ary searc h a lgorithm searches a range of elements for a value. If the val ue is found, the function returns true. Otherwise, it retu rns false. For example, the following function call , which appea rs in line 44 , searches all the elemenrs in vect for the value 7. binary_search(vect.begin(), vect.end( ), 7)

3

linclude <iostream> linclude <vector> II Needed to def ine the vector 'include <algorithm> II Needed for the count algorithm using namespace std;

uh a

4 5

II Th is program demonstrates the STL count algorit hm.

m

1 2

m

Progtam 16-16 demonstrates the count algorithm.

6

7 8

M

9 10

in t main() { II Define a vector object . vector<int> values ;

11

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1017

us uf

i

16.5 Introduction to the Standard Template library (STl )

II Def i ne an iterator for the vector.

12 13

vector<int>: : iterator iter:

14

II Store some values in the vector. values . push_back(!); values.push_back(2);

15 16 17

Yo

values.push_back(2); values . push_back(3);

18

19 20 21 22 23 24 25 26 27

values.push_back(3); values.push_back(3); II Display the values in t he vector. cout « cout «

az

cout « "The values in the vector are:\n"; for (iter = values.begin(); iter < values.eod(); iter++ )

*iter «

endl «

" "; endl;

Ri

28

29 30

II Display the count of each number. cout « "The number of Is in the vector is "i

31

cout « cout « cout «

count(values.begin(l, v a lues . e nd ( ) , 1) « "The number of 2s in the vector is " • count(values.begin(), values. end ( ) , 2 ) « cout « "The number of 3s in the vector is • cout « count(values . begin(), values . end ( ) , 3 ) « return 0;

37

an

36

.

)

end l ; end l ;

Ha

Program Output The values in the vector are :

...

endl;

ss

32 33 34 35

1 2 2 3 3 3

ad

The number of Is in the vector is 1 The number of 2s in the vector is 2 The number of 3s in the vector is 3

m

Program 16-17 demonstrates the max_element and min_element algorithms. Program 16-17

'include <iostream> 'inc l ude <vector> 1/ Needed to define the vector 'include <algorithm> / / Needed for the algorithms using namespace std;

uh a

4

I I A demonstration of the max element and min element algorithms

m

1 2 3 5 6

, 7

M

9 10

intmain( ) {

II Define a vector object . vector<int> numbers;

11

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 16-17

i

Chapter 16 Exceptions, Templates, and the Standard Template library (STL)

(continued)

us uf

1018

II Define an iterator tor the vector. vector< i nt> :: iterator iter;

12

13 14 15

,. 17

Yo

II Store some numbers in the vector. for (int count = 0; count < 10 ; count++) numbers.push_back(count);

16

1/ Display the numbers in the vector.

19 20 21 22 23

caut « "The numbers in the vector are: \n" ; for (iter numbers.begin(); ite r != numbers.end(); iter++)

=

cout «

*iter «

endl «

" "; endl;

az

cout «

24

II Find the largest value in the vector . iter

= max_e l ement(numbers . begin(),

caut «

numbers.end(»;

"The largest value in the vector is " «

28

endl ;

endl;

an

31

The numbers in the vector are:

Ha

1 2 3 4 5 6 7 8 9

ss

)

Program Output

o

*iter «

II Find the smallest value i n the vector. iter = mio_element(numbers . begin(), numbers.end(»): cout « "The smallest value in the vector is " « *iter « return 0 ;

29 30 32 33

Ri

25 26 27

The largest value in the vector is 9 The smallest value in the vector is 0

Program 16· 18

.

m

3 4 5

II A demonstrat i on of the STL find algorithm. 'inc lude <iostream> ' include <vector> II Needed to define the vector ' include <algorithm> II Needed for the find a l gorithm using namespace std:

6

intmain() {

uh a

7

m

1 2

ad

Program 16· 18 demonstra tes the find algorithm.

II Define a vector object. vector<int> numbers;

II Define an iterator for the vector . vector<int>::iterator iter:

M

9 10 11 12 13 14

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1019

II Store some numbers in the vector. for (int x = 0; x < 10; x++) numbers.push_back(x);

15 16 17 18

II Display the numbers in the vector. cout « "The numbers in the vector are:\n"; for (iter = numbers.begin(); iter != nUmbers.end(); iter++) cout « *iter « " "; cout « endl « endl;

22 23

2.

}

Ri

26 27 28 29

az

II Find the number 7 in the vector. iter = find(numbers.begin{), numbers . end(), 7); cout « *iter « endl; return 0;

25

Program Output The numbers in the vector are:

o

Yo

19 20 21

us uf

i

16.5 Introduction to the Standard Template Library (STl)

1 2 3 4 5 6 7 8 9

an

7

Program 16-19 demonsuates the for_each algorithm.

3

• 5

II A demonstration of the for_each algorithm. 'include <iostream> 'include <vector> II Needed to define the vector 'include <algorithm> II Needed for the for each algorithm using namespace std;

Ha

1 2

ss

Program 16-19

6

8 9

II Function prototype void doubleValue{int &); int main() (

II Define a vector object. vector<int> numbers;

m

"

15

II Define an iterator for the vector. vector<int>::iterator iter;

uh a

16 17

m

10 11 12 13

18

19

20

ad

7

II Store some numbers in the vector. for (int x = 0; x < 10; x++) numbers.push_back(x);

21

M

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

16~ 19

(continued)

22

/1 Display the numbers in the vector.

23

cout « "The numbers in the vector are:\n"; for (iter numbers.begin(); iter != numbers . end(); iter++)

=

cout «

·iter « " endl « endl;

cout «

26

"j

Yo

24 25 27

II Double the values in the vector. for_each(numbers.begin(), numbers . end(), doubleValue)i

28 29 30

31

II Display the numbers in the vector again.

32

cout <:< "NOW the numbers in the vector az:-e:\n"; for (iter numbers . begin(); iter != numbers.end(); iter++)

35 36

" ";

Ri

cout « *iter « cout « endl; return OJ

az

=

33 34

37

us uf

Program

i

Chapter 16 Exceptions, Templates, and the Standard Template library (STL)

1020

)

38

39 11-·······*·*·***-**··_·_---*--*·_--*·_-***---*---*--- **** 40

/1 Function doubleValue . This function accepts an int

4S

void doubleValue(int &val)

{

val· '" 2;

)

ss

47 48

Ha

"

an

41 II reference as its argument. The value of the argument • 42 II is doubled . • 43 II···················································· .... 44

Program Output The numbers in the vector are : 012 3 4 567 8 9

ad

Now the numbers in the vector are: o 2 4 6 8 10 12 14 16 18

m

In line 29, the following statement calls for each:

m

for_each(numbers.begin(), numbers.end(), doubleValue) ;

uh a

The first and second arguments specify a range of elements. In this case, the range is the enti re vec[or. The third argument is the name of a funct ion. The for_ each algorithm calls the function once fo r each element in the range, passing the element as an argument to the fun ction.

The programs in this section give you a brief introduction to using the STL by demonstrat-

M

ing simple operations on a vector. In the remaining chapters yo u w ill be given specific examples of how ro use othet STL containers, irerarors, and algorithms.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

102 1

i

Review Q uestions and Exercises

us uf

Review Questions and Exercises Short Answer 1. What is a th row point? 2. What is an exception handler?

Yo

3. Expl ain the difference between a try block and a catch block.

4. What happens if an exception is thrown) bur not caught? 5. What is " unwinding the stack"?

az

6. Wha t happens if an exception is thrown by a cl ass's member function? 7. How do you prevent a progra m from halti ng when the new operator fails to allocate memory?

Ri

8. Why is it more convenient to write a function template than a series of overloaded fu nctions? 9. Why must you be careful when writing a function template that uses operators such as [1 with its parameters?

an

"10. What is a container? What is an iterator?

11, What twO types of containers does the STL provide?

ss

12. What ST L algorithm randomly shuffles the elements in a container ?

Fill-in-lhe-Blank

Ha

13. The line containing a th row statement is known as the _____ 14. The block contains code that di rectly or indirectly might cause an exception to be thrown .

15. The _ _ _ _ block handles an exception.

ad

16. When writing function or class templates, you use a{n} generic data type.

to specify a

17. T he beginning of a template is marked by a(n) _ _ __

m

18. When defini ng: objects of class templates, the

you wish to pass into the

type pa rameter mllst be specified.

m

19. A{n ) _ __ _ templ<'lte works with a specific da ra rype.

container organizes data in a sequential fashion sim ilar to an array.

21. A(n )

container uses keys to rapidly access elements.

uh a

20. A( nJ

22.

23, The

are pointer-like objects used to access data sto red in a container. exception is thrown when the new operator fa ll s to allocate the

M

requesrcd amounr of memory.

Algorithm Workbe nch 24. Write a function that searches a numeric array for a specified value. T he function shou ld return the subscript of the clement containing the value if it is found in the array . Ii (he value is not fou nd, the function should throw an exception.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 16 Exceptions, Templates, and the Standard Template Library (STL)

i

1022

us uf

25. Write a function that dynamically allocates a block of memory and returns a char pointer to the block. The function should take an integer argument that is the amount of memory to be allocated. If the new operaror cannot allocate the memory, the function should return a null pointer (a pointer to address 0). 26. Make the function you wrote in Question 24 a template.

28. A program has the following definition sta tements: vector<int> numbers;

vector<int> :: iterator iter;

Yo

27. Write a template for a funct ion that displays the contents of an array of any type.

az

Write code that uses the iterator to display all the values stored in the vector.

30. A program has the following definition: vector<double> numbers;

Ri

29. Write a statement that performs the STL binary_search algorithm on the vector defined in Question 28 .

void display(double nJ {

cout ÂŤ

n ÂŤ

endl;

ss

)

an

The same program a lso has the following function:

True or False

Ha

Write code that uses the STL for_each algorithm to display the elemen ts of tHe numbers vector using the display function.

31. T 32. T 33. T

F F

There can be only one catch block in a program.

F

34. T

F

Data may be passed wirh an exception by storing it in members of an exception class. Once an exception has been thrown, it is not possible for the program to jump back to the throw point.

m

ad

When an exception is thrown, bur not caught, the program ignores the error.

F

m

35. T 36. T

F

The compiler creates an instance of a function template in memory as s60n as it encounters the template.

37. T

F

38. T 39. T

F

A class object passed to a function template must overload any operators used on the class object by the template. Only one generic type may be used with a template.

F

In the function template definition, it is not necessary to use each type parameter declared in the template prefix.

40. T 41. T

F F

It is possible to overload twO function templates. It is possible to overload a funct ion template and an ordinary (nontemplate)

F

function. A class template may nOt he derived from another class template.

uh a M

All type parameters defined in a function template must appear at least once in the function paramerer list.

42. T

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 10 2 3

43. T 44. T 45. T

F F F

Specialized templates work with a specific data type.

46. T

F

STL algorithms are implemented as fu nction templates.

A class template may not be used as a base class.

us uf

i

Review Questions and Exercises

Yo

W hen defining an iterator from the STL, the compiler automatically creates the right kind, depending upon the container it is to be used with.

Find the Error

Each of the following declarations or code segments has errors. Locate as many as possible.

47. catch

az

(

quotient - divide(numl, num2); cout « "The quotient is " « quotient « )

Ri

try (char *exceptionString) (

cout «

endl;

exceptionString;

)

an

48. try (

quotient - divide(numl, num2); )

ss

cout « "The quotient is " « quotient « catch (char *exceptionString) (

exceptionStringi

Ha

cout « )

endl;

49. template <class T> T square{T number) (

ad

return T * T; )

50. template <class T> int square(int number)

m

(

return number· number;

m

>

51 . template <class TI, class T2> Tl sum(Tl x, Tl y)

uh a

(

return x + y;

)

52. Assu me the following definition appears in a program that uses the SimpleVector

M

class template presented in this chapter. int <5impleVector> array(25);

53. Assume the following statement appears in a program that has defined valueSet as an object of the SimpleVector class presented in this chapter. Assume that valueSet is a vector of ints, and has 20 elements. cout «

valueSet<int>{2] «

endl;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1024

i

Chapter 16 Exceptions, Templates, and the Sta ndard Template library (STL)

us uf

Programming Challenges 1. Date Exceptions

Modify the Date class you wrote for Programming Cha llenge 1 of Chapter 13. T he class should implement the fo llowing exceprion classes: T hrow when an invalid day « 1 or > 31) is passed to the class.

InvalidMonth

Throw when an invalid month « 1 or > 12) is passed to the class.

Yo

InvalidDay

Demonstrate the class in a driver program. 2. Time Format Exceptions

az

Mod ify the MilTime class you created for Programmi ng Challenge 4 of Chapter 15. The class should implement the following exceptions:

T hrow when an invalid hour « 0 or > 2359) is passed to the class.

BadSeconds

Throw when an invalid number of seconds « 0 or > 59) is passed to the class.

Demonstrate the class in a driver program.

Ri

BadHour

an

3. Minimum/Max imum Templates

Ha

4 . Absolute Valu e Template

ss

Write templates fo r the two functions mi nimum and maximum. The minimum function should accept twO arguments a nd return the value of the argument that is the lesser of the two. T he maximum fun ction sho uld accept two arguments and return the value of the argument tha t is the greater of the two. Des ign a simple driver program that demonstrates the templates with various da ta types.

ad

Write a funcrion template that accepts an argument and retu rns its absolute value. The absolute value of a number is its va lue with no sign. For example, the absolute value of -5 is 5, a nd the absolute value of 2 is 2. Test the template in a simple driver program.

5. Total Template

m

m

Write a template for a function called total. The function should keep a running total of va lues entered by the user, then return the total. T he argu ment sent into the function should be the num ber of values the function is to read . Test the template in a simple driver program that send s values of vari ous types as arguments and displays the results.

6. IntArray Class Exception

M

uh a

Chapter 14 presented a n IntArray class that dynamically crea tes an array of integers and performs bounds check ing on the array. If an invalid subscript is used with the class, it displays an error message and aborts the program. Modify the class so it throws an exception instead.

7. TestScores Class Write a class named TestScores . The class constructOr should accept an array of test scores as its argument. The class should have a member function that returns the average of the test scores. [f any test score in the array is nega tive or greater than 100, the class should throw an exception. Demonstrate the class in a program.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1025

i

Review Quest ions and Exercises

us uf

8. SimpleVector Modification

Yo

Modify the Simplevector class template presented in this chapter to include the member functions push_back and pop_back, These functions shou ld emulate the STL vector class member functions of the same name. (See Table 16-5.) The push_back function should accept an argument and insert its value at the end of the array. The pop_back function should accept no argument and remove the last element from the array. Test the class with a driver program. 9. SearchableVector Modification

Modify the SearchableVector class template presented in th is chapter so that it performs a binary search instead of a linear search. Test the template in a driver program.

az

10. Sortablevector Class Template

Ri

Write a class template named SortableVector. The class should be derived from the SimpleVector class presented in this chapter. It should have a member function that sorts the array elements in ascending order. (Use the sorting algorithm of your choice.) Test the template in a driver program. 11. Inheritance M odification

12. Specialized Templates

ss

an

Assuming you have completed Programming Challenges 9 and 10, modify the inheritance hierarchy of the Searchable Vector class template so it is derived from the SortableVector class instead of the SimpleVector class. Implement a member function named sortAndsearch, both a sort and a binary search.

Ha

In this chapter, the section Specialized Templates within Section 16.4 descri bes how to design templates that are specialized for one particular data ty pe. The section introduces a method for specializing a version of the SimpleVector class template so it will work with strings. Complete the specialization for both the Si.mpl.eVector and SearchableVector templates. Demonstrate them with a simple driver program.

ad

13. Rainfall vector

m

Modify Programming Challenge 2 in Chapter 7 (Rainfall Statistics) ro use an STL vec+ ror instead of an array. Refer ro the information in Tables 16-5 and 16-6 if you wish to use any of the member functions. 14. Test Scores vector

uh a

m

Modify Programming Cha llenge 2 in Chapter 9 (Test Scores #1) to use an STL vector instead of a dynamically allocated array. Refer to the information in Tables 16-5 and 16-6 if you wish to use any of the member functions.

15.

sn Binary Search

Modify programming Challenge 1 in Chapter 8 (Change Account Validation) so it uses a vector instead of an array. Also, modify the program so it lIses the STL binarY_Search algorithm to locate valid account numbers.

M

-

16. Exception Project

Solving the

Exception Project Problem

This aSSignment assumes you have completed Programming Challenge 1 of Chapter 15 (Employee and ProductionWorker Classes). Modify the Employee and Productionworker classes so they throw exceptions when the fo llowing errors occur:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Exceptions, Templates, and the Standard Template Library (STl)

i

Chapter 16

The Employee class should throw an exception named InvalidEmployeeNumber when it receives an employee number that is less than 0 or greater than 9999. The ProductionWorker class should throw an exception named InvalidShift when it receives an invalid shift. The Productionworker class should throw an exception named InvalidPayRate when it receives a negative number for the hourly pay rate.

us uf

• •

Yo

1026

Write a driver program that demonstrates how each of these exception conditions works. 17. Phone Book Vector

Ri

az

This chapter has an accompanying video note that shows how ro store an object in a vector. After you view that video, write a class named PhoneBookEntry that has members for a person's name and phone number. Then write a program tbat creates at least five PhoneBookEntry objects and stores them in a vector. After the objects are stored in the vector, use a loop to display the contents of each object in the vector.

an

Serendipity Booksellers Software Development ProjectPart 16: A Problem-Solving Exercise For this chapter's exercise, you are ro implement exception handlers to intercept critical errors (such as memory allocation failures, file open failures, etc.).

Ha

ss

First, locate each point in the program where the inventory file is opened. If the program fails {Q open the file, an exception should be thrown. The exception handler should display an urgent crror message indicating the nature of the problem, and terminate the program.

M

uh a

m

m

ad

The second modification will be in the cashier function. In Chapter 15 you modified that function to ask how many titles the customer is purchasing, and dynamically allotate an array of SoldBook objects large enough to hold that many titles. In the event that the new operator fails to allocate the required memory, the cashier function should throw an exception. Once again, the exception handler should display an urgent error message and terminate the program.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

L

az

rJ

Introduction to the Linked List ADT

17.4

'7.2

Linked List Operations

17.5

17.3

A Linked List Templa te

Variations of the linked List

The STL l ist Container

ss

an

17.1

Ri

TOPICS

Ha

Introduction to the Linked List ADT CONCEPT: Dynamically allocated d ata structures m ay be linked togeth er in to form a chain.

m ~ll1 ory

m

ad

A linked list is a series of connected nodes. where each node is a data Stfl]cture. A lip ked lise can grow or shrink in size as the program runs. This is possible because the nodes in a linked list are dynamically allocated . 1ÂŁ new data need to be added to a linked list, the program simply allocates another node and inserts it inco the se ries. If a particular piece of data needs to be removed from rhe linked Jist, the program deletes the node containing that dala.

m

Advantages of Linked Lists over Arrays and vectors

htc

uh a

Although linked lists are more comp lex to code and manage than arrays, they some distinc t advantages. First, a link ed list can easily grow or shrink in size. In fa c t , fhe programmer doesn't nt:ed to know how many nodes will be in t he list. They are s impl y created in memory as they are needed.

M

One might argue that linked lists are not superior to vectors (found in the Standard template Library), beca use vectors, too, can expa nd or shrink. The advan tage that linked IlStS have

1027

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 17

Linked Lists

us uf

i

1028

Yo

over vectors, however, is the speed at whi ch a node may be inserted into or deleted from the lise. To insert a value into the middle of a vector requires all the elements below the insertion point to be moved one position toward the vecto r 's end, thus mak ing room for the new value. Likewise, removing a va lue from a vector requires all the element~ below the removal point fa be moved one position toward the vector's beginni ng. When a node is inserted into or deleted from a linked list, none of the other nodes have to be moved.

The Composition of a Linked List

az

Each n0de in a linked list contains one or more members that represent data. (Perhaps the nodes hoJd invento ry records, or customer na mes, addresses, and telephone num bers.) In addi tion to the da ta , each node contains a pointer, which can point to another node. The make up of a node is il lustrated in Figure 17-1 .

Ri

Figure 17-1

Pointer /"

an

Data Members

Ha

ss

A linked list is cal led "linked" because each node in the series has a pointer char points to the next node in the list. T his creates a chain where the first node points to the second node, the second node poims (Q the third node, and so on. T his is illustrated in Figure 17-2. Figure 17-2

List Head

NULL

ad

& 1 1+ 1 1+ Ic---o-<---.J+

uh a

m

m

The list depicted in Figure 17 -2 has three nodes, plus a poi nter known as the list head. The head simply points to the fir st node in the list. Each node, in turn, points ro the next node in the list. The fi rst node points to the second node, wh ich points to the third node. Because the third node is the last one in the list, it points to the NULL address (address 0) . T his is usually how the end of a linked list is signi fi ed- by lening the last node poim to NULL.

M

()

NOTE : Figure 1 7-2 depicts the nodes in the lin ked list as bei ng very close to each other, nea tl y arra nged in a row. In reality, th e nodes may be scattered around various parts of memory.

Dec:laratlons So how is a linked list created in C++? First yo u must decla re a data structure that will be used for the nodes. For exa mple, the follow ing struct could be used to create a list where

each node holds a double:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1029

i

17.2 Linked List Operations

us uf

struct ListNode (

double value ; ListNode *nexti ) ;

b9

Yo

T he first member of the ListNode Str ucture is a double named value. It will used to hold the node's data. The second member is a pointer named next. T he pointer ean hold (he addre~s of any object that is a ListNode .sttuct~re. This allows each ListNo1e structure to pOin t to the next ListNode structure In the lIst.

az

Because the ListNode str ucture contains a pointer ro an object of the sa me tYPr as [hat being declared, it is known as a self-referential data structure. This structure mak~s it possible to create nodes that point to other nodes of the same type. The next step is ro define a pointer to serve as the list head, as shown here.

Ri

ListNode *head ;

'S

an

Before you use the head pointer in any linked list operations, you must be sure it initia lized to NULL, because that marks the end of the list. Once you have declared a n~de data structure and have created a NULL head pointer, you have an empty linked list. The next step is to implement operations with the JiSt.

~ Checkpoint

Describe the twO parts of a node. What is a list head? W ha t signifi es the end of a linked list?

17.4

Wha t is a self-referential data structure?

Ha

ss

17. 1 ] 7.2 ] 7.3

ad

Linked List Operations CONC EPT: T he ba sic linked list operarions are a ppending a node, traversing rIie list,

m

inserting a node, deleting a node, and destroying the li st.

m

1 ~1 th is s~c t ion we will develop an abstract data t~pe that perfo.rms basic I.in ked l il' ~ opera-

uh a

tions Ll Slng the r>istNode structu re and head pOInter defined In the prevIOUS sec Ion. We will use the following class declaration, which is stored in NumberList. h.

Contents of NumberList . h

1

M

2 3

II Specification file for the NumberList class titndef NUMBERLIST H 'define NUMBERLIST_H

4

5 6

class NumberList {

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1030

Linked Lists

private: 1/ Declare a structure for the list struct ListNode

10 11 12

(

13 14

};

15

ListNode *headj

I.

1/ List head pointer

pUblic :

18

1/ Constructor

19

NumberList()

20 21

az

17

II The value in this node II To point to the next node

Yo

double value; struct ListNode *nexti

{ head = NULL: }

22 23

II Destructor -NumberList() i

"25 29

an

II Linked list operations void appendNode(double); void insertNode(double); void de!eteNode(double);

26 27 28

Ri

7

8 9

us uf

i

Chapter 1 7

void displayList() canst; );

31

'endif

ss

30

Ha

Norice that the constructor initializes the head pointer to NULL. This establishes an empty linked list. The class has member flmctions for appending, inserting, and deleting nodes, as well as a displayList funct ion that displays all the values stored in the list. T he destructor destroys the list by deleting all its nodes. These functions are defined in NumberList . cpp. We will examine the member functions ind ividual ly.

ad

Appending a Node to the List

m

m

Create a new node . Store data in the new node. If there are no nodes in the list Make the new node the first node. Else Traverse the list to find the last node. Add the new node to the end at the list. End If.

M

uh a

Appendi ng a Node 10 a Linked LiSt

To append a node to a linked list means to add the node to the end of the list. The appendNode member function accepts a double argument, num. The function will allocate a new ListNode structu re, store the value in num in the node's value member, and append the node to the end of the list. Here is a pseudocode representation of the general algorithm:

Here is the actua l C++ code for the fun ction: 11 12 13 14

void NumberList :: appendNode(double num) { ListNode *newNode; II To point to a new node ListNode *nodePtr; /1 To move through the list

15

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

17.2 Linked Li,t opeca,;J ,

"

20 II If there are no nodes in the list

21 22 23 24

i

Yo

II make newNorle the first node.

us uf

/1 Allocate a new node and store nurn there . newNode = new ListNode; newNode->value - nurn; newNode->next = NULL;

16 17 18

1031

i f (!head)

head = newNode; else II Otherwise, insert newNode at end.

25 26 27 28 2. 30 31

{

az

II Initialize nodeptr to head of list. nodePtr = head; II Find the last node in the list .

32

33

Ri

while (nodeptr->next) nodeFtr = nodePtr- >nextj

II Insert newNode as the last node .

34 35

nodePtr->next

36

=

newNode;

}

37

an

}

Let's examine the statements in detail. In lines 13 and 14 the fu nction defines the follow ListNode *newNode;

ListNode *nodePtr;

ss

ing loca l variables:

/1 To point to a new node /1 To move through the list

Ha

The newNode pointer will be used to allocate and point to the new node. The l Odeptr pointer will be used to travel down the linked list, in search of the last node. The following statements, in lines 17 through 19, create a new node and StOre num in its value member:

ad

newNode ~ new ListNode; newNode->value - num; newNode->next : NULL ;

l

m

The statemenr in line 19 is important. Because this node will become [he last node in the list, its next pointer must point to NULL.

m

In line 23, we rest the head pointer to determine whether there are any nodes al eady in the list. If head points to NULL, we ma ke the new node the first in the list. Makt g head point to the new node does this. Here is the code; ,

uh a

if

(!head) head"" newNode:

If head docs not point to.NULL, however, there are nod e.s in the.list. The else paft of the

M

i f statement mllst contam code to find the end of the Itst and JOsert the new nl de. The

code, in lines 25 through 36, is shown here: else {

II In itialize nodePtr to head of list.

nodePtr :: head;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 1 7 linked lists

us uf

i

1032

II Find the last node in the list. while (nodePtr->nextj nodePtr = nodePtr->next; II Insert newNode as the last node. nodeptr - >next = newNode;

Yo

)

The code uses nodePtr to travel down the list. It does rhis by first assigning nodeptr to head in line 28: nodePtr

=

head ;

Ri

while (nodeptr->next) nodePtr ~ nodeptr->next;

az

The while loop in lines 31 and 32 is then used to traverse (or travel through) the list searching for the last node. The last node will be t he o ne whose next member points [Q NULL:

When nodePtr points co the last node in (he list, we make its next member point to newNode in line 35 with the following statement. =

newNode;

an

nodePtr->next

This inserts newNode at the end of the list. (Remember, newNode - >next already points to

ss

NULL. )

Program 17-1 demonstrates the functio n.

Ha

Program 17-1

II This program demonstrates a simple append II operation on a linked list .

3 4 5

'i nc l ude <iostream> Jinclude "NumberList.h" using namespace std ;

1

6

7

int main{)

8

{

II Defi ne a NumberList object. NumberList l ist;

m

9

ad

2

10 11 12 13

m

II Append some values to the list. list . apgendNOde(2 . 5 ); list . appendNOde(7 . 9); list . appendNOde(12.6); return 0 ;

14

uh a

15 16 17

)

M

(This program displays no output.)

Let's step through the program, observing how the appendNode func tion bu ilds a linked list to store the t hree argument values used. The head pointer is declared as a private member variable o f the NumberLis t class. head is initialized to 0 (NU LL) by the NumberList constructor, w hich indicates that the list is empty.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1033

i

17.2 Linked List Operatio,ns

us uf

The first caJi to appendNode in line 13 passes 2.5 as the a rgument. In the fo llowirg sta te+ ments, a new node is allocated in memory, 2.5 is copied imo its value memper, and NULL is assigned to the node's next pointer:

Yo

newNode = new ListNodej newNode->value = num; newNode->next = NULLi Figu re 17+3 illustrates the state of the head pointer and the new node.

NU l l

head 2 .5

f+

NULL

Ri

&

az

Figure 17+3

newNode

an

The next sta tement to execute is the fo llowing i f statement: if (!head)

head = newNode j

ss

ne'fNodej is Because head poinÂŁs to NULL, the condition Ihead is true. The statemem head executed, making newNode the first node in the list. This is illustrated in Figure 17-4.

Ha

Figure 17-4

NUl l

newNode

IJ

m

ad

head

uh a

m

There are no more Statements to execute, so contro l returns to function main. the second call (0 appendNode, in line 14, 7.9 is passed as the argument. Once again the first three statements in the function create a new node, store the a rgument in the nod ~ 's value ' member, and assign its next pointer to NULL. Figure 17-5 illustrates the current state of the list and the new node.

M

Figure 17-5

~

head

7.9

3--

NULL

newNode

IL._'_._5---L_T ::l . NUll J

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1034

us uf

i

Chapter 1 7 Linked lists

Because head no longer points to NULL, the else part of the i f statement executes: else

II Otherwise, insert newNode at end.

{

1/ Initialize nodePtr to head of list . nodePtr = head;

Yo

II Find the last node in the list . while (nodeptr- >next) nodePtr = nodeptr->next; II Insert newNode as the last node. nodePtr- >next = newNode;

az

}

Ri

The first statement in the else block assigns the value in head to nodeptr. This causes nodeptr to point to the same node that head poi nts to. This is ill ustrated in Figure J 7-6.

Figure 17-6

+NULL

an

7.9

newNode

NULL

Ha

ss

+

nodeptr

M

uh a

m

Figure 17-7

m

ad

Look at the next member of the node that nadeptr po ims to. Its value is NULL, which means that nodeptr->next also poims to NULL. nadePtr is already at the cnd of the list, so the while loop immediately terminates. T he last statement, nodePtr - >next newNodej ca uses nodePtr- >next to point ro the new node. This inserts newNode at the end of the list as shown in Figure 17-7.

NULL

head

newNode

nodePtr

The third time appendNode is called, in line 15, 12.6 is passed as the argument. Once again, the first three statementS create a node with the argument stored in the valu;e member. T his is shown in Figure 17-8.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

, 7.2 linked list Ope ra tio~s

us uf

i

103 5

Figure 17路8

12 . 6

Yo

NULL

'+NUlL

newNode

Figure 17-9

I:T

12.6

+

NULL

newNode

Ha

nodePtr

NULL

ss

an

7.9

Ri

az

Next, the else part of the if statement executes. As before, nodePtr is made ro point to the same node as head, as shown in Figure 17-9.

Because nodePtr->next is not NULL, the while loop will execllte. After its fi~st itera tion, nodeptr will point to the second node in the list. This is shown in Figure 1 7~ 1 0 .

M

uh a

m

m

ad

Figure 17-10 NU LL

12 . 6

+

NUl L

newNode

nodePtr

The while loop's conditional test will fail after the first iteration because nodeptr->next now poims ro NU LL. The last statement, nodePtr- >next = newNode;1 causes nodePtr - >ne xt to poim to rhe new node. This inserts newNode at the end of t~e list as shown in Figure 17-11 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 17

Linked Lists

Yo

us uf

i

1036

NUll

newNode

Ri

Figure 17-1 1 depicts the final state of the linked list.

az

nodePtr

Traversing a Linked List

an

T he appendNode fu nction demonstrated in the previous section contains a wh il e loop that traverses, or travel s through the linked list. In this section we w ill demonstrate the displayList member function that traverses the list, displaying the value member of each node. The following pseudocode represents the algo rithm.

End While .

Ha

ss

Assign List head to node poi nter. While node pointer is not NULL Display the value member of the node poin t ed to by node pointer . Assign node pointer to its own next member .

T he function is shown here: 45 46

void NumberList !: displayList() canst {

48

49

II To move through the list

II position nodePtr at the head of the list. nodePt r - head ;

m

SO 51

ListNode *nodeptr;

ad

47

II While nodePtr points to a node, traverse II the list .

52 53 54 55

m

while (nodePtr) { II Di splay the value i n this node . cout ÂŤ nodePtr- >value ÂŤ endl;

56

uh a

57 58 59 60

M

61 62

II Move to t he next node . nodePtr = nodePt r->next; } }

Program 1 7~ 2 , a mod ificatio n of Program 1 7~ 1 , demonstrates the function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1037

Program 17路 2 II This program demonstrates the displayList member function . 'include <iostream>

linclude "Number List. h

4 5

using names pace std:

6 7

int main()

H

Yo

3

II Define a NumberL ist object . NumherList list ;

11 12 13

II Append some values to the list . list .appendNOde ( 2 . 5); list . appendNode( 7.9);

14

1ist . appendNOde(12 . 6) :

15 16 17 18 19

II Display the values in the list . list.displayList() ; return 0 ;

az

{

8 9 10

Ri

1 2

us uf

i

17.2 linked list operati9ns

an

)

Program Output

2.5

ss

7."

12 . 6

Ha

Usually, when an operation is to be performed on some or all the nodes in a linked list, a [fa路 versal algorithm is used. You will see va riations of this algorithm throughout this c9apter.

Inserting a Node

m

m

ad

Append ing a node is a stra ightforward procedure. Inserting a node in the middl e bf a list, however, is more in volved. For example, suppose the values in a list are sorted ~nd you wish all new val ues to be inserted in their proper position. This w ill p rese rve the :Order of the list. Using the ListNode structure aga in, the following pseudocode shows an alga. rithm for findi ng a new node's proper position in the list and inserting it there. -nhe algorithm assumes the nodes in the list are already in order.

uh a

Create a new node . Store data in the new node . If there are no nodes in the list Make the new node the fir8t node . Else Find the fi~st node whose value is greater than or equal to the new value, or the end of the list (whichever is first) . Insert the new node before the found node, or at the end of the list if no such node was found . End If.

M

Inserting a Node in a Linked List

Notice that the new algorithm finds the fi rst node whose va lue is greater than or ~q u a l to the new va lue. The new node is then inserted before the found node. This witl requ ire the

use of rwo node poinrers during the traversa l: one ro po int ro the node being it;Ispected

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 17 linked lists

us uf

i

1038

and another to point to the p revious node. The code for the traversal a lgorithm is as follows. (As before, num holds the value being inserted into the list.)

/1 Initialize previousNode to NULL . previous Node = NULL;

II Skip all nodes whose value is less than num. while (nocleptr 1= NULL t & nodePtr - >value < num)

Yo

II position nodePtr at the head of list. nodeptr = head;

{

az

previousNode = noclePtri nodePtr = nodePtr->next i }

70 71 72 73

void NumberList: : insertNode(doub1e num) { ListNode *newNode; II A new node ListNode *nodePtr; 1/ To traverse the list ListNode 路previousNode ~ NULL; 1/ The previous node

an

69

Ri

T his code segment uses the ListNode poinrers nodePtr and previous Node. previous Node always points to the node before the one pointed to by nodePtr . The enrire insertNode funct ion is shown here:

76 77 78

II Allocate a new node and store num there . newNode = new ListNode i newNode - >value = num;

Ha

75

ss

74

80

II I f there are 110 lIude!:; i n the li::;t II make newNode the fi r st node

81

if ( ! head)

82

{

93 84

85 86

} else {

m

87 88 89

head - newNode ; newNode - >ne xt ~ NULL;

ad

79

II Otherwise , insert newNode

II position node Ptr at the head of list . nodeptr = head;

m

90

Initialize previousNode to NULL . - NULL;

91

II

"

prev~ou8Node

uh a

93 9S

II Skip al l nodes whose value is less than num . while (nodePtr ! = NULL && nodeptr->value < num)

96

{

94

previous Node = nodePtr; nodePtr = nodePtr-> next;

97

M

98 99

100

101 102 103 104

1/ If the new node is to be the 1st in the list ,

II inse rt it before all other nodes. if (previousNode == NULL) {

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

10 39

head" newNodei newNode - >next = nodePtri

105 10' 107 lOS

)

112

Yo

else II Otherwise insert af t er the previous node. { previousNode- >next = newNodei newNode->next = nodeptr;

109 110 II I 113

us uf

i

17.2 Linked List Operatiors

} }

114

az

Program 17-3 is a modification of the Program 17-2. it uses the insertNode member fun ction to inserr a value in its ordered position in the list.

Program 17-3.

II This program demo ns trates the insertNode member function.

2 3

'include <iostream> 'include "NumberList . h" using namespace std;

4

Ri

1

6

int main()

7

{

II Define a NumberList object . NumberList list;

8 9

ss

10

an

5

Bui l d the list with some values. list.appendNOde(2.5) ; list.appendNOde(7.9l; lis t . appe ndNOde(12 . 6);

II

11

Ha

12 13 14 15

16

II Insert a node in the middle of the list . list . insertNode (10 . 5l;

17

IS 20 21

)

m

22

ad

II Dispay the list list.displayList( ); return 0;

19

2.5 7.'

uh a

10 . 5 12.6

m

Program Output

M

Like Program 17-2, Program 17-3 calls the appendNode function three times to ~uild the list with the values 2.5, 7.9, and 12.6. The insertNode function is then called, with the argument 10.5.

In insertNode, a new node is crea ted a nd the function argument is copied to its value m<;:mbcr. .Be<;all~ e the li:>t alr<;:ad y has nodes stored in it, thJ else parr of the .iÂŁ statement will cxc<;ute. It begins by assigning nodeptr [Q head. Figure 17-12 illuStrates the state of t he list at this poi nt.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 17 Linked lists

us uf

i

1040

Figure 17-12

Yo

nodeptr

az

NULL

Ri

?

newNode

shown in Figure 17-13.

ad

Ha

ss

Figure 17-13

an

Because nodePtr is not NULL and nodeptr->value is less than num, the while I~op will iterate. During the iteration, previousNode will be made to point to the nOfe that nodePtr is pointing to. nodePtr will then be advanced [0 point to the next node., This is

m

NULL

newNode

uh a

m

previous Node

M

Once again, the loop performs its test. Because nodePtr is not NULL and nodeptr->value is less tha n num, the loop will iterate a seco nd time. During the seco nd itera ti on, borb previousNode an d nodePtr are adva nced by one node in the lise. This is shown in Figure 17-14.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 17.2 linked list Operati~ns

i

1041

us uf

Figure 17- 14

Yo

nodePt r

previoUSNode

Ri

newNode

az

NULL

an

T his time, the loop's test will fail because nodePtr - >value is not less than num. T he statemems after the loop will execute, which cause previousNode->nf!xt to poim [Q newNode, and newNode - >next to point to nodePtr. Th is is ill ustrated in Figu re 17-15.

ss

Figure 17-15

Ha

nodeptr

~,---------,Lj 2.5

NULL

ad

head

newNode

m

m

pre viousNode

uh a

T his leaves the list in its final state. If you follow the links, from the head pointer to the NULL, YOLL will see that the nodes are stored in the order of their value members .

M

~ Checkpoint 17.5

Wha t is the difference between appending a node to a list and inserting a node infO a list?

17.6 17.7

Which is easier to code: appending or inserting? Why does the inse rtNode function shown in this section use a previous Node pointer ?

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 17 linked lists

1042

us uf

Deleting a Node Deleting a node fro m a linked list requires two steps :

1. Remove the node from the list without breaking the links created by the next pointers.

2. Delete the node from memory.

Yo

az

{

ListNode *nodePtr ; ListNode *previousNode;

124 125

126 127

II To travers e the l ist II To point to the previous node

an

II If the list is empty, do nothing . if (!head) r e turn;

12 8 129 130

131 13 2

II Determine if the first node is the o ne. if (head- >value == num )

1J J

{

nodePtr = head - >next; delete head; head = nodePtr;

134

135

136 137

} els e

13 8 1 39 140 1 41 142 143 144 145

{

m

ad

/1 I ni tialize nodePtr to head of list nodePtr m head;

m

146

II Skip all nodes whose value member is /1 not equal to num. while (nodePtr l= NULL && nodeptr->va lue ! = num) {

1 47 1 48

previousNode = nodePt r; nodePtr - nodePtr->nexti

14.

uh a

)

150 15 1 1 52

M

Ri

void NumberList ::deleteNOde(double num)

122 123

ss

Linked List

Ha

-

Deleting a Node from a

The deleteNode member function sea rches for a node containing a particular value and deletes it from the list. It uses an algorithm simi lar to the i nsertNode func tion. Two node pointers, nodePtr a nd previous Node, 3re used to t raverse the list . previousNode always points to the node whose position is just before the one pointed to by nodePtr. When nodeptr po ints to the node tha t is to be d eleted, previous Node-> next is made to poim to nodePtr->next. This removes the node pointed to by nodeptr from the list. T he final step performed by this funct io n is to free the memory used by the node with the delete operator. T he entire func tion is shown below.

153

II If nodePtr is not at the e nd o f the list, II l i nk the prev iou s node to the node after II nodeptr , then delete nodePtr .

I S'

if (nodePtr)

155

{

156 157 159 15 9 160

previoUSNode- >next delete nodePtr:

= nodeptr - >next;

} }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1043

17.2 Linked List OperatiQns

Program 17~4

3 4

II This program demonstrates the deleteNode member function. 'include <iostream> finclude " NumberList . h" using namespace std;

5

int main() { II Define a NumberList object. NumberList list;

11

II Build the list with some values . list . appendNode(2 . 5); list . appendNode(7 . 9); list . appendNOde(12.6);

12 13 14 15

/1 Display the list . cout « "Here are the initial values:\n"; list . displayList(); cout « end1;

18 19

20 1/ Delete the middle node . cout «

23 24 25 26

list.deleteNOde(7.9);

ss

21 22

an

16 17

az

7 8 9 10

Ri

6

i

Yo

1

2

1nd chen

us uf

Program 17~4 demonsrrares rhe funcrion by first building a list of three nodes, deleting them one by one.

Ha

"Now deleting the node in the middle. \n";

II Display the list. cout « "Here are the nodes left. \n" ; 1ist.disp1ayList(); cout « end1;

27 28 29 30

ad

II Delete the last node .

31

cout «

32 JJ 34 35

list . deleteNode( 12.6);

"Now deleting the l a st nod e . \n";

m

II Display the l ist. cout « "Here are the nodes l eft. \n"; list.displayList(); cout « endl;

36

m

37

38

39

/1 Delete the only node left in the list. cout « "Now delet i ng the only remaining node. \n"; list.deleteNode(2.5);

uh a

40 41

42 43

1/ Display the list. cout « "Here are the nodes left.\n"; 1ist.displaytist(); return 0;

M

44 45 46

47

} (program output i ontinues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

P ..og ..am 17-4

linked lists

i

Chapter 17

(continued)

us uf

1044

P..ogram Output Here are the initial values: 2. , 7.,

Yo

12.6 Now deleting the node in the middle. Here are the nodes left. 2.'

az

12.6

Now deleting the last node. Here are the nodes left .

Ri

2.5 Now deleting the only remaining node . Here are the nodes left .

an

To illustrate how de1eteNode works, we will step through rhe fi rst ca ll which deletes the node contai ning 7.9 as its value. Thi s node is in the midd le of the list.

Ha

ss

In the deleteNode function, look at the else parr of the second i f statement. This is lines 138 through 159. This is where the function w ill perform its action since the list is nOt empty, and the first node does nOt conta in the value 7.9. Just like inser tNode, this func tion uses nodeptr and previous Node to trave rse the list. The wh ile loop in lines 145 through 149 termina tes when the value 7.9 is located. At th is point, the list and the other pointers will be in the stare depicted in Figure 17-16.

GI--- r'1---'--,

ad

Flgu ..e 17-16

f

nodeptr

uh a

m

m

~'--'-2.5~

7.' NULL

[j-1 previous Node

M

Next, the following statemenr in line 156 exec mes: previousNode->next

~

nodePtr->next;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 17.2 linked list Operati9ns

i

1045

us uf

This Statement ca uses (he links in the list to bypass t he node that nodePtr points roo Although the node sti ll exists in memory, this removes it from the list, as illustrated in Figure !?-! ?

I

NULL

Ri

az

Yo

Figure 17-17

previous Node

Destroying the List

ss

the node.

an

Th e statement in line 157 uses the delete operator ro complete the total deletion of

Ha

It's impoctant for t he class's destructo r to release aU the memory used by the list. If d oes so by stepping through the tist, deleting o ne node at a time. The code is shown here: : 167

NumberList::-NumberList()

168

{

ListNode *nodePtri ListNode *nextNode;

169 170 173

174

II While nodePtr is not at the end of the list ... while (nodeptr != NULL)

m

175

II position nodePtr at the head of the list. nodePtr = head;

ad

171 172

m

176 177 178 179

uh a

180 181

II position nodePtr at the next node. nodePtr = nextNode;

18'

185 186

M

II Save a pointer to the next node. nextNode = nodePtr- >next; II Del ete the current node. delete nodePtr;

182 183

187

II To traverse the list II TO point to the next node

}

}

Notice the use of next Node instead o f previous Node. The next Node poin ter i~ used to ho ld the position of the next node in t he list, so t hat it will be available after the node pointed to by nodePtr is deleted.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1046

Li nked Lists

us uf

i

Chapter 17

~ Checkpoint

What are the twO steps involved in deleting a node from a linked list?

17.9

When deleting a node, why can't you just use the delete operator to remove it from memory? Why must you take the steps you listed in response to Question 17.8?

17.10

In a program that uses several linked lists, what might eventually happen jf (he class destructor does not destroy its linked list?

Yo

17.8

az

A Linked List Template

Ri

CONCEPT: A template can be easily created to store linked lists of any type.

The limitation of the NumberList class is that it can only ho ld double values. The class can easily be converted to a template that will accept any data type, as shown in the fol lowing code. (This file is stored In the Student Source Code Folder Chapter 17

an

\LinkedList Template Version 1.)

ss

Contents of LinkedList . .h (Version 1)

{

m

13 14

ad

Ha

1 II A class template for holding a linked list. 2 lifndef LINKEDLIST_H 3 'define LINKEDLIST H 4 'include <iostream> II For cout and NULL 5 using namespace std; 6 7 template <class T> e class LinkedList 9 { 10 private : 11 II Declare a structure for the list . 12 struct ListNode

,. 15

m

i.

}

,

T value ; struct ListNode *next ;

II The value in this node II To point to the next node

17

ListNode *head;

II List head pointer

uh a

19 20 public :

21 22

23

II Constructor NumberList() { head - NULL; }

M

24

25 26

II DestrUctor -NumberList();

27

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 17.3 A linked list Template

31 32 33 };

i

II Linked list operations void appendNOde{T): void insertNode(T); void deleteNode(T): void displayList{) const;

us uf

28 29 30

34

Yo

35

37 II 38 II

appendNode appends a node containing the va l ue passed into newValue, to the end of the list.

39 11**************************************************

II II

To point to a new node To move through the list

46

54 55 56 S?

58

5' 60 61 62 63

6'

an

=

II II

If there are no nodes in the list make newNode the first node. i f (Ihead) head = newNode; else II Otherwise, insert newNode at end. { II Initialize nodeptr to head of list . nodePtr = head;

ss

53

II Allocate a new node and store nurn there. newNode new ListNodei newNode->value = nurn; newNode->next = NULL;

Ha

48 49 50 51 52

II Find the last node in the list. while (nodePtr->nextj

ad

47

Ri

ListNode *newNode; L i stNode *nodept r ;

az

40 41 template <class T> 42 void LinkedList<T>::appendNode(T newValue) 43 { 44 45

nodeptr -

nodep t r->next;

II Insert newNode as the last node. 66 nodeptr->next = newNode; 67 ) 68 ) 69 70 11************************************************** 71 II displayList shows the value 72 II stored in each node of the l i nked list 73 II pointed to by head.

M

uh a

m

m

65

1047

74 11************************************************** 75 76 template <class T> 77 void LinkedList<T>::displayList() 78 { 79 ListNode *nodePtr; II To move through the list 80 81 II Position nodeptr at the head of the list. 82 nodePtr head;

=

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

83 84

/1 While nodeptr points to a node, traverse II the list .

85 86 B7 88 89

while (nodePtr)

{ II Display the value in this node. cout « nodeptr->value « endl;

90

91 92 93 94

us uf

i

linked lists

Yo

Chapter 17

1048

II Move to the next node. nodePtr = nodePtr->nexti } }

9S

az

96 11·*··*········_············_··-_······-·---_··_·_--

97 II The insertNode function inserts a node with 98 II newValue copied to its value member.

• •

Ri

99 1/***·**·**····**·**·····**······**········**···**··

II A new node 1/ To traverse the list II The previous node

II Allocate a new node and store num there . newNode B new ListNode; newNode->value ~ num;

ss

108 109 110

newValue)

an

100 10 1 template <class T> 102 void LinkedList<T> :: insertNode{T 103 ( ListNode *newNode; 104 ListNode *nodePtr; 105 ListNode ·previousNode : NULL; 10' 107

Ha

III

112 113

II If there are no nodes in the list II make newNode the first node.

114

if (!head)

115

{

118

119 120

}

else 1/ Otherwise, insert newNode . { // position nodePtr at the head of list . nodePtr ~ head;

m

121 122

head = newNode; newNode->next ~ NULL;

ad

116 117

123

1/ Initialize previousNode to NULL . previ ousNode ~ NULLj

127

131

/1 Skip all nodes whose value is less than num. while (nodePtr 1= NULL && nodePtr->value < num) { previous Node = nodePtr; nodePtr = nodePtr->nexti

132

}

uh a

m

124 125 126

128 129

M

130

133

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 17.3 A Linked List Template

137

(

head'" newNodei newNode - >next = nodePtr;

140

)

141

else

142 143 144

{

1/ Otherwise insert after the previous node.

previousNode->next = newNode; newNode->next = nodePtr;

145

)

146

Yo

138 139

us uf

136

/1 If the new node is to be the 1st in the list, /1 in~0rt it before aLl other nodes. if (previousNode == NULL)

}

148

149 11*****··· __

az

147 }

·· _---_·_·_ --*·_*-_·_*_·_-----------_·_---*

Ri

150 II The deleteNode function searches for a node 151 1/ with searchValue as its value. The node, if found, 152 II is deleted from the l ist and from memory. 153

154

i

134 1).

• * *

11------------------------------_·_-------------------*

155 template <class T> {

ListNode *nodePtr; ListNode *previousNode;

1.0

return;

1/ Determine if the first node is the one. if (head->value :: num) {

nodePtr : head->nexti delete head;

head

174

m

175 176 177

178

M

uh a

179

= nodePtri

}

else

m

166 167 168 169 170 171 172 173

II If the list is empty, do nothing. if (!head)

Ha

164 165

II To point to the previous node

ad

161 162 163

II To traverse the list

ss

15 9

an

156 void LinkedList<T>::deleteNode(T searchValue)

157 158

{

II Initialize nodePtr to head of list. nodePtr = head; II Skip a11 nodes whose value member is II not equal to num. while (nodePtr != NULL && nodeptr->value ! : num)

180 181 182

{

183

)

1049

previousNode - nodePtr; nodePtr = nodeptr->nexti

184 185

II If nodePtr is not at the end of the list,

16.

II

187

II nodePtr, then delete nodePtr.

1LoK the prevLous node to the node after

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Linked lists

if (nodePtr)

188 189

(

previousNode->next

190 191

nodePtr- >next;

delete nodePtri

192

)

193

}

194 }

Yo

195 196 197 /1 Destructor 198 1/ This function deletes every node in the list.

us uf

Chapter 1 7

1050

1/········********··············****···**···········• •

199 11.···**···········**·················*··** ·········

200

205

Ri

az

201 template <class T> 202 LinkedList<T>::-LinkedList() 203 { ListNode *nodeptr; II To traverse the list 204

II To point to the next node

ListNode *nextNode;

206 207 208

1/ position nodeptr at the head of the list . nodeptr head;

209 210 211 212

/1 while nodeptr is not at the end of the list ... while (nodePtr !~ NULL)

an

=

{ nextNode

ss

1/ Save a pointer to the next node .

213 214 215 216 217

= norlePtr- >next;

Ha

II Delete the current node. delete nodeptr;

218 219

II position nodePtr at the next node .

220

nodePtr

222 }

}

ad

221

= nextNodei

223 ' endif

m

Note that the template uses the - -, !-, and < relational operators to compare node values, and it uses the« operator with cout to d isplay node values. Any type passed ro the template must support these operators.

M

uh a

m

Now let's sec how the template can be used to create a list of objects. Recall the Feetlnches class that was introd uced in Chapter 14. That class overloaded n umerous operarors, incl ud ing "'=, <, and «. In the Chapter l7\Lin)c;.edList Template version 1 folder we have included a mod ified version of the Feetlnches class that also overloads the I = operator. Program 17-5 is stored in that same folder. This program uses the LinkedList template to create a linked list of Feetlnches objects.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1051

i

17.3 A linked list Template

Yo

II This program demonstrates the linked list template. 'include <iostream> Hnclude "LinkedList . h" linclude "Feet Inches . h" using names pace std; int main() { II Define a LinkedList object. LinkedList<FeetInches> list :

11

,

II Define some FeetInches objects . inches FeetInches distancel (5, 4) ; II 5 feet FeetInches distance2(6, 8) ; II 6 feet 8 inches FeetInches distance3(B, 9) ; II 8 feet 9 inches

12 13

Ri

14 15 16

az

1 2 3 4 5 6 7 8 9 10

us uf

Program 17-5

II Store the Feetlnches objects in the list . list . appendNOde(distancel); /1 5 feet 4 inches list . appendNOde(distance2): // 6 feet 8 inches list . appendNOde(distance3); // a feet 9 inches

17 IS 19 20

an

21

1/ Display the values in the list . cout « "Here are the initial va l ues : \n" i list . displayList(); cout « endl;

27

1/ Insert another FeetInches object. cout « "Now inserting the value 7 feet 2 inches . \n"; FeetInches distance4(7, 2); list.insertNode(distance4);

Ha

ss

22 23 24 25 26 28 29 30 31

II Display the values in the list. cout « "Here are the nodes now . \n"; list . displayList(); cout « endl;

ad

32 33 34 35

36

m

m

// Delete the last node . cout « "Now deleting the last node. \n"; FeetInches distance5(B, 9); list . deleteNOde{distance5);

1/ Display the values in the list. cout « "Here are the nodes left. \n" ; list.displayList(); return 0;

uh a

37 3B 39 40 41 42 43 44 45 46

)

M

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Linked lists

Program 17-5

i

Chapter 17

(continued)

us uf

1052

Program Output Here are the initial values : 5 feet, 4 inches

Yo

6 feet , B inches B feet, 9 inches

Now inserting the value 7 feet 2 inches . Here are the nodes now. 5 feet, 4 inches 6 feet, B inches

7 feet,

2 i nches

az

,

feet, 9 inches

Now deleting the last node.

Ri

Here are the nodes left. S feet, 4 inches 6 feet, B inches

Using a Class Node Type

an

7 feet , 2 inches

Ha

struct L istNode { T value;

ss

In the LinkedList class template, the following structure was used to create a data type for the linked list node.

struct ListNode *next; } ;

ad

Another approach is to use a separate class template to create a data type for the node. Then, the class constructor can be used to store an item in the value member and set the next pointer to NULL. Here is an example:

{

m

template <class T> class ListNode

uh a

m

pUblic; T value; ListNode<T> *nexti

II Node value II Pointer to the next node

II constructor ListNode (T nodeValue)

{ value

= nodeValue;

next'" NULLi}

} ;

M

The LinkedList class template can t hen be written as the following:

template <class T> c l ass LinkedList {

private:

ListNode<T> *headi

II List head pointer

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 17.3 A linked list Template

i

10S3

us uf

public : II constructor LinkedList ( ) { head = NULL; }

Yo

II Destructor -LinkedList() i II Linked list operations vo i d appendNOde(T)i void insertNode(T)i void deleteNOde(T); void displayList() const ;

az

) ;

an

newNode = new ListNode i newNode->value = newValue; newNode->next - NULL;

Ri

Because the ListNode class constructor assigns a value to the value member and sets the next pointer to NU LL, some of the code in the LinkedList class can be simplified. For example, the following code appears in the previous version of the LinkedList class template's appendNode func tion:

newNode

= new

ss

By using the ListNode class template w ith irs consrructor, these three lines of code can be reduced to one: ListNode<T>(newValue); 17 \LinkedList Template

Ha

(This file is stored in the Studcm Source Code Folder Chapter Version 2. )

Contents of LinkedList. h (Version 2) 1 // A class template for holding a l i nked list .

ad

2 // The node type is also a class template.

3 'ifndef LINKEDLIST H 4 'define LINKEDLIST H

m

5 6 // *** *** **** ************** ** *** ** **************

7 /1 The ListNode class creates a type used to

* *

m

8 1/ store a node of the linked list.

10

uh a

11 template <class T> 12 class ListNode 13 {

14 public : // Node value 15 T value; 16 ListNode<T> *nextj // Pointer to the next node

M

17

18

1/ Constructor

19

ListNode (T nodeValue) { value = nodevalue; next: NULL;}

20 21

22 }; 23

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

32

Yo

30 { 31 private :

/1 List head pointer

ListNode<T> ·head;

33 34 public :

/1 constructor LinkedList()

37

{

head'" NULL;

}

az

35 36 38

41

45

II Linked list operations void appendNode(T); void insertNode(T); void deleteNode(T)i

46

void displayList() canst;

43 44

an

42

Ri

II Destructor - LinkedList();

39 40

us uf

11·······_····························· __ ······* 11······**···*****·***··**·····················

24 25 /1 LinkedList class 26 27 28 template <class T> 29 class LinkedList

i

Chapter 17 linked lists

IOS4

47 };

ss

48 49

Ha

51 II appendNode appends a node containing the value 52 II passed into newValue, to the end of the list. 53 54

• •

55 template <class T>

56 void LinkedList<T>;:appendNOde(T newValue) {

ListNode<T> *newNodei ListNode<T>

~nodePtr;

1/ To point to a new node // To move through the list

1/ Allocate a new node and store newvalue there. newNode = new ListNode<T>(newValue);

m

59 60 61 62 63 64

ad

57

58

uh am

65

66 67 68

M

6'70

II It there are no nodes ~n the 1~8t II make newNode the first node . i f (!head) head newNode; else II Otherwise, insert newNode at end.

=

71

II Initialize nodeptr to head of list. nodePtr = head;

72 73 74 75

II F~nd the last node in the list. while (nodeptr->next) nodePtr ~ nodeptr - >next;

76

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH , 7.3 A linked List Templ~te

79

us uf

7B

i

II Insert newNode as the last node . nodePtr->next = newNode;

7J )

Yo

80 ) 81 82 11************************************************** 83 II displayList shows the value stored in each node * * 84 II of the linked list pointed to by head. 85 11************************************************** 86 87 template <class T> 88 void LinkedList<T> ::displayList() const 89 {

II To move through the list

az

ListNode<T> *nodePtr;

90 91

92

II Position nodePtr at the head of the list . nodeptr = head;

93

Ri

94

II While nodePtr points to a node, traverse II the list .

95

96

while (nodePtr)

97 98 99 100 101

(

an

II Display the value in this node. cout « nodeptr- >value « endl:

104

ss

I I Move to the next node. nodePtr = nodePtr->next;

102

103

)

Ha

105 } 106

107 11************************************************** 108 II The insertNode function inserts a node with * 109 I I newValue copied to its value member. * 110 11**************************************************

ad

1 11

112 template <class T>

113 void LinkedList<T>::insertNode(T newValue) 114 { 115

118 119 120

II Allocate a new node and store newValue there. newNode ~ new ListNode<T>(newValue):

m

m 116 117

ListNode<T> *newNode; II A new node ListNode<T> *nodePtr; II To traverse the list ListNode<T> *previousNode = NULL; II The previous node

uh a

121 122

II If there are no nodes in the list II make newNode the first node .

123 124

if (Ihead)

125

{

head = newNode; newNode->next = NULL :

M

126

127 128

1055

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Linked Lists

129

else

130

{

i

Chapter 17

1/ Otherwise, insert newNode.

/1 position nodeptr at the head of list. nodePtr = head ;

131 132 133

/1 Initialize previous Node to NULL. previousNode = NULL;

134 135 137 138 139

II Skip all nodes whose value is less than newvalue. while (nodeptr != NULL && nodeptr - >value < newValue) {

previous Node

=

nodeptri nodeptr = nodePtr->next;

140 141 142

az

)

143

Ri

II If the new node is to be the 1st in the l i st, 1/ insert it before all other nodes. if (previousNode ~= NULL)

144 145 146 147

{

head'" newNode i

148 }

151

else

152 153 154 155 156

{

an

newNode->next • nodeptr;

149 150

/1 Other wise inser t after the previous node .

=

ss

previ ousNode->next n e wNode; newNode->next = nodePtr ; }

}

Ha

157 ISS

1/ The delete Node function searches for a node II with searchValue as its value. The node, if found, II is deleted from the list and from memory.

• + +

ad

II·*+****·*+~·~******~**·~ +~+++· ++ +· +*~****+*+**+*+*+++

template <clas s T> void LinkedList<T> :: dele t eNode(T searchValue) { ListNode<T> * nodePtri II To traverse the l i st ListNode<T> *previousNode; II To poi nt to the previous node

m

160 161 162 163 16. 165 166 167 168 16 9

Yo

136

us uf

1056

m

170

uh a

171 172 173

II If the list is empty, do nothing . if (!head) return ;

174

M

175

176

II Determine if the fir st node is the o ne . if (head->value -- sear chValue)

177

{

178 179 180

=

nodePtr head->next ; delete head ; head nodePtr;

=

181

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1057

else

183

{

184

II Initialize nodeptr to head of list nodeptr '" head;

185 186

II Skip all nodes whose value member is II not equal to nurn. while (nodePtr 1- NULL

190

{

&,

nodeptr->value !- searchValuej

Yo

187 188 189

previousNode = nodePtr; nodeptr ~ nodePtr- >next;

191 192 193 194 19 5 196

us uf

182

i

, 7.3 A Linked List Template

az

II If nodePtr is not at the end of the list, II link the previous node to the node after

II nodePtr, then delete nodeptr. i f (nodePtr)

previouSNode->next delete nodePtr;

202

E

}

nodePtr- >next;

}

an

203

Ri

197

198 199 200 201

209

ss

204 } 205 206 II** ·~*·*~**·*··_·~***T****TT*.***.**~.***.***.*.**~ 207 II Destructor • 208 II This function deletes every node in the list. * II* ·**·~·**~*T************** TT.*******~**.**********

217 218 219

uh am

222 223

II While nodePtr is not at the end of the list ... while (nodePtr !~ NULL) {

224

225 226

II Position nodePtr at the next node. nodePtr = nextNode;

230

M

II Save a pointer to the next node. next Node = nodePtr- >next; II Delete the current node . delete nodePtc;

227 228 229 231

II To traverse the list II To point to the next node

II Position nodePtr at the head of the list. nodePtr = head;

m

220 22 1

ListNode<T> *nodePtr; ListNode<T> *nextNode;

ad

21 3 { 214 215 21'

Ha

210 211 template <class T> 212 LinkedList<T>::-LinkedList()

}

232 233 'endH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 17 Linked Lists

us uf

i

]058

Variations of the Linked List

Yo

CONCEPT: There are many ways [0 link dynamically all oca ted data structu res together. Two variations of the linked list are the doubly linked list and the circu lar linked list.

~

"""

â&#x20AC;˘.

Ri

az

The linked Jist examples that we have discussed are considered singly linked liSl1: Each node is linked to a single other node. A variation of this is the doubly linked list. In this type of list, each node points not only to the next node, but also to the previous one. This is illustrated in Figure 17-18.

PoirIIII'

t

list Head

"""

NU L

ss

N ULL

..

",,"'w

an

Poirller

.......

Ha

In Figure 17-18, the last node and rhe first node in the list have poinrers to th9 NULL address. When the program traverses the list it knows when it has reached eithe r end. Another variation is the cirClilarly linked list. The last node in this type of list pOinJs to the

first, as shown in Figure 17-19.

ad

Figure 17-19

G--[

I+~

1+1

M

uh a

m

m

list Head

1+[

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1059

us uf

i

17.5 The STL list Contain'er

The STL list Container

Yo

CONC EP T : T he Standard Template Library provides a linked list container.

az

The list container, found in the Standard Template Library, is a template version of a doubly linked list. STL lists can insert elements or add elements to their front quicker than vectors can, because lists do not have to shift the other elements. lists are also efficient at adding elements at their back because they have a built-in pointer to the last element in the list (no traversal required). Table 17-) describes some of the list member functions.

Ri

Table 17-1

Member Functio n back

an

empty

Examples and Description cout « list.back() « endl; The back member func tion returns a reference to the last element in the list. i f (list .empty()) The empty member func tion returns true if the list is empty. If the list has elements, it returns false. iter = list.end(); end returns a bidirectional iterator to the end of the list. list.erase(iter) ; list.erase(firstlter, lastlter ) The first example causes the list element pointed to by the iterator iter to be removed. The second example causes all of the list elements from first.lter to las titer to be removed. cout « list.front() « endl; front rerurns a reference to the fi rst clemenr of the list. list.insert(iter, x) The insert member fu nction inserts an element into the list. This example inserts an eiemen r with the value x, just before the elemem pointed to by iter. listl . merge(list2) ; merge inserts all the items in list2 into listL listl is expanded to accommodate the new elements pl us any elements already stored in listl. merge expects both lists to be sorted. When list2 is inserted into liStl, the elements are inserted into their correct position, so the resulting list is also sorted. list .pop_back(); pop_back removes the last element of the list. list.pop front(); pop_front removes the firsr element of the list. list . push back(x) ; push_backlnserts an element with value x at the end of the list. list.push front ( x); push= front insetts an element with value x at the beginning o f the Jist.

ss

end

Ha

erase

ad

front

m

insert

M

uh a

m

merge

push_back

(table continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1060

(continued)

M ember Function

us uf

Table 1 7~ 1

i

Chapter 17 linked lists

Examples and Description

reverse

list.reverse()i

reverse reverses the order in which the elements appear in the li st.

s i ze swap

Yo

Returns the number of elements in the lis t . listl . swap(list2)

T he swap mem ber fu nction swaps the elements stored in twO lists. For example, assuming listl and list2 are lists, th is statement will exchange the val ues in the two lists. unique

az

list . unigue{);

unique removes any element that has the same value as the element before it.

Ri

Program 17-6 demonstrates some simple operations with the list container. Program 17-6

/1 This program demonstrates the STL list container. 'include <iostream>

3 4

'include <list> II Include the list header. usi ng names pace std :

a 9

int main() { II De f ine a list object . lis t< i nt> myList;

Ha

6 7

ss

5

an

1 2

II Define an iterator for the list . list<int>: : iterator ite r;

13 14 15 16

II Add values to the list . for (int x ~ 0; x < 100; x +- 10) myList . push_bacK(x);

ad

10 11 12

17 18

1/ Display the values. for (iter = myList . begin ( ); iter != myList.end(); iter++)

m

19

cout « '"iter « cout « endl;

" ";

23 24 25 26

/1 Now reverse the order of the elements. myList.reverse() ;

uh a

m

20 21 22

II Display the values again . for ( iter - myList . begin(); iter != myList.end(); iter++) cout « "ite r « .. " ; cout « endl; return 0;

27 28

29

M

30 31

)

Progrilllm Output

o

10 20 30 40 50 6 0 70 60 90 90 80 70 60 50 40 30 2 0 10 0

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

Review Questions and Exercises Short Answer

us uf

i

1061

1. What are some of the advantages thar linked lists have over arrays?

2. What advantage does a linked list have over the STL vector?

Yo

3. What is a list head? 4. What is a self-referential data structure?

5. How is the end of a linked list usually signified? 6. Name five basic linked list operations.

az

7. What is the diffe rence between appending a node and inserting a node?

8. What does "traversing the list" mean? twO

steps required

to

delete a node from a linked list?

Ri

9. What are the

10. What is the advantage of using a template to implement a linked list? 11. What is a singly linked list? What is a doubly linked list? What is a circularly linked list?

an

12. What type of linked list is the STL list container?

Fill-in-the-Blank

ss

13. The _ _ _ _ points to the first node in a linked list.

Ha

14. A data structure that points to an object of the same type as itself is known as a{n) _ _ _ _ data structure. 15. After creating a linked list's head pointer, you should make sure it points to _ _ _ _ before using it in any operations.

16.

a node means adding it

17.

a node means adding it to a list, but not necessari ly to the end.

the end of a list.

ad

to

18. _ _ _ _ a list means traveling through the list.

19. In a{n) _ _ _ _ list, the last node has a pointer to the first node.

m

20. In a(n)

list, each node has a poimer to the one before it and the one after it.

m

Algorithm Workbench 21. Consider the following code: struct ListNode

uh a

{

int value; struct ListNode *nexti

M

};

ListNode *head;

II List head pointer

Assume that a linked list has been created and head points to the first node. Write code that traverses the list disp laying the contents of each node's value member. 22. Write code that destroys the linked list described in Question 21.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

us uf

23. Write code that defines an STL list container for holding float values.

i

Chapter 17 linked lists

1062

24. Write code that stores the values 12.7, 9.65, 8.72, and 4.69 in the list container you defined for Question 23.

25. Write code that reverses the order of the items you stored in the list container in Question 24.

26. T

F

Yo

True or False

The programmer must know in advance how many nodes will be needed in a

linked list.

27. T 28. T 29. T

F F F

In physical memory, the nodes in a linked list may be scattered around.

3D. T

F

Linked lists are not superior to SlL vectors.

31. T

F

Deleting a node in a linked list is a simple matter of using the delete operawe

az

It is not necessary for each node in a linked list to have a self-referentia l pointer.

to free the node's memory.

F

A class that builds a linked list should destroy the list in the class destructor.

an

32. T

Ri

When the head pointer points to NULL, it signifies an empty liSt.

Find the Error

ss

Each of the following member functions has errors in the way it performs a linked list operation. Find as many mistakes as you ca n. 33. void NumberList::appendNOde(double num)

Ha

{

ListNode *newNode, *nodePtr; 1/ Allocate a new node & store num newNode = new l istNode; newNode_>value = num;

ad

// If there are no nodes in the list /1 make newNode the first node.

m

if (! head) head newNodei else II Othorwise, insert newNode.

uh a

m

{

II Find the last node in the list . while (nodePtr- >next) nodePtr = nodePtr->next; II Insert newNode as the last node. nodeptr->next = newNode;

)

)

34. void NumberList::deleteNOde(double num)

M

{

ListNode *nodePtr, *previousNode; II If the list is empty. do nothing. i f (! head) return; // Determine if the first node is the one. if (head->value == num)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises

i

1063

us uf

delete head; else {

II Skip all nodes whose value member is II not equal to nurn . while (nodePtr->value != nurn) {

previous Node = nodePtri nodePtr = nodePtr - >next;

Yo

II Initialize nodeptr to head of list. nodePtr :: head;

)

) )

35. NumberList: :-NumberList{)

Ri

az

II Link the previous node to the node after II nodePtr, then delete nodePtr. previousNode->next = nodeptr->next; delete nodePtr ;

{

an

ListNode *nodePtr, *nextNodei nodeptr == head: while (nodeptr ! = NULL)

ss

{

Ha

nextNode a nodeptr->next; nodeptr->next = NULL; nodePtr = nextNodei )

)

Programming Challenges

ad

1. Your Own l inked l ist

m

Design your own linked list class to hold a series of integers. The class shou ld have member funct ions for appending, insening, and deleting nodes. Don't forget to add a destructor that destroys the list. Demonstrate the class with a driver program.

m

2. List Prim

uh a

Modify the linked list class you created in Programming Challenge 1 to add a print member function. The functio n should display all the values in the linked list, Test the class by starting with an empty list, adding some elements, and then printing the resulting list out.

M

3, List Copy Constructor Modify your linked list class of Programming Challenges 1 and 2 to add a copy construcror. Tesr your class by making a list, making a copy of the list, and then displaying the values in the copy.

4. List Reverse Modify the linked list class you created in the previous programming challenges by adding a member function n:;amed reverse that rearranges the nodes in the list so that their order is reversed. Demonstrate the function in a simple driver program.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

linked lists

i

Chapter 17

1064

us uf

S. List Search

Yo

!"10dify the linked list ~Iass you created in the previous programming challenges to ~nclLlde. a me~ber function named search chat returns the position of a specific value l ~ the hnked list. The fi~st node in the Jjst is at position 0, the second node is iH pu,si~ two 1, and so on . If x IS nOt found on the list, the search should return -1. Test the new member function using an appropriate driver program. 6. M e mber Insertion by Position

Problem

az

7. Member Removal by Position

Ri

by 1'0si ti 0 l1

Modify the list class you created in the previous programm ing c hallenges by adding a member function for deleting a node at a specified position. A value of 0 for the posi ~ tion means that the firs t node in the list (the current head) is deleted. The function does nothing if the speci fi ed position is greater than or equal to the length of the list.

an

Solving the Member Insertion

Mod ify the list class you created in the previous programming challenges by adding a member function fo r inserting a new item at a speci fied position. A posicion of 0 means that the value will become the first item on the list, a position of 1 means that the value will become the second item on the list, and so on. A position equa l to or grea ter than the length of the list mea ns that the va lue is placed at the end of the list.

S. List Template

program~

ss

Create a list class template based on the list class you created in the previous ming ch:dlenges. 9. Rainfall Statistics Modification

Ha

Modify Programming Chal lenge 2 in Chapter 7 (Rainfall Statistics) to let the user decide how many months of data will be entered. Use a linked list instead of an array to hold the monthly data. lO. Payroll Modification

ad

Modify Programming C hallenge 10 in Chapter 7 (Payroll ) to use three linked lists

m

instead of three arrays to hold the employee IDs, hours worked, and wages. When the program starts, it should ask the user to enter the employee IDs. There should be no limit on the number of IDs the user ca n enter.

List Search

uh a

m

Modify the LinkedList tem plate shown in this chapter to include a member function named search. The function should search the Jist fo r a specified value. If the value is fo und, it shou ld return a number indicating irs position in the list. (The first node is node 1, the second node is node 2, and so forth.) If the va lue is nOt fo und , the fun c~ tion should return O. Demonstrate the function in a driver program.

M

12. Double Merge Modify the NurnberList class shown in th is chapter to include a member function named mergeArray. The mergeArray function should take an array of doubles as its firSt argument, and an integer as its second argument. (The second argument will specify the size o f the array being passed into the first argument. )

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises

i

1065

us uf

T he function should merge the values in the array into the linked list. The value in each element of the array should be inserted (not appended) into the linked list. When the values are inserted, they should be in numerical order. Demonstrate the Junction with a driver program, When you are satisfied with the function, incorporate it into the LinkedList template.

Yo

13. Rainfa ll Statistics Modifica ti on #2

Modify the program you wrote for Programming Challenge 9 so that it saves the data in the linked list to a file. Write a second program that reads the data from the fi le into a linked list and displays it on the screen.

az

14. Overloaded [] Operator

an

Ri

Modify the linked list class that you created in Programming Challenge 1 (or the LinkedList template presented in this chapter) by adding an overloaded [J operator function . This will give rhe linked List the ability to access nodes using a subscript, like an array. The subscript 0 will reference the first node in the list, the subscript 1 will reference the second node in the list, and so forth. T he subscript of the last node wiU be the number of nodes minus 1. 1ÂŁ an invalid subscript is used, (he funct ion should throw an exception.

15. pop and pu s h Member Functions

Ha

ss

The STL list container has member funct ions named pop_back, pop_front, push_back, and push_front, as described in Table 17-1. Modify the linked list class that you created in Programming Challenge 1 (or the LinkedList template presented in' this chapter) by add ing your own versions of these member functions.

Serendipity Booksellers Software Development ProjectPart 17: A Problem-Solving Exercise

m

m

ad

Currently, the inventory data is stored in an array of 20 InventoryBook class objects. For this chapter's assignment, you will implement a linked list, which will take the place of the array. When done, your program should allow the user to ente r as many books into inventory as needed. 1. Remove the isEmpty and removeBook member func tions from the InventoryBook class. Because the InventoryBook objects will be stored in a linked list, it is no longer necessary to use these funct ions, 2. Modify the linkedList template presented in this chapter. The template must be

uh a

able to store InventoryBook class objects. Tf you intend to use the == operator, it will need to be overloaded in the InventoryBook class. Also, you will need to add a memo ber function that searches the linked list for a specific book. and returns a reference or pointer to that object. This will be necessary to execute the InventoryBook member

M

functions.

3. There are several parts of the program that are coded to use the InventoryBook array. Modify the remainder of the program so it works successfully with rhe linked list.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m

m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

o o

18. t 18. 2 18.3 18.4

18.5

Introd uction to the Stack ADT Dynamic Stacks The STL st ack Container Introduction to the Queue ADT

Ri

az

l

Dynam ic Queues

ss

an

18.6 The STL deque and queue Containers

Ha

Introduction to the Stack ADT

ad

A stack is a data structure that stores and retrieves items in a lasr-inl-firstout ma nner.

Definition

m

m

Like a~ aTTay or a linked list, a stack is a data structure that holds a sequence of ~Iements. Un like arrays and lists, however, stacks are last-tn, first-ollt (LIFO) structures. Th;is means that ~hen a program retrieves elements from a stack, (he last element inserted into the stack is the first one retrieved (and likewise, the first element inserted is the last one rcrcie:"ved ). Whe Visua liZin g the way a stack works, think of a stack of pla tes at the begin oing of a cafete ia line. When a cafeteria worker replenishes rhe Sllpply of pla tes, the first qne he or she p tS on the stack is the last one taken off. T his is illustra ted in Figure 18-1. I

uh a

1

M

The L FO cha racteristic of a stack of plates in a ca feteria is a lso the pri mary cha raCteristic of a yack data structure. T he last data dement placed on rhe stack is the ~rst data rerrie\{ed from the sta ck .

1067

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1068

us uf

i

Chapter 18 Stacks and Queues

Figure 18-1

First plate in, lasl plale out

---+ ---+

5

4

Yo

Last prate in, first plate out

2 1

az

Applications of Stacks Stacks are useful data srructures for algorithms that work first with the last saved element of a series. For example, computer systems use stacks while executing programs. When a

Ri

function is called, they save the program's retu rn add ress o n a stack. They also create loca l

an

variables on a stack. When the function terminates, the loca l variables are removed from the stack and the return address is retrieved. Also, some calcularors use a stack for performing mathematical operations.

Static and Dynamic Stacks

Ha

ss

There arc twO types of stac k data structun:: sta tic and dynamic. Static stacks have a fixed size, and are implemented as arrays. Dynamic stacks grow in size as needed, and are implemented as linked lists. In this section yOLl will see examples of both static and dynamic stacks.

Stack Operations

ad

A stack has two primary operations: push and pop. The push operation causes a value to be stored, or pushed onto the stack. For example, suppose we have an empty integer stack that is capable of holding a maximum of three values. With that stack we execute the fol lowing push operations.

m

push(5)i

push(lO) ; puSh(lS);

m

Figure 18-2 illustrates (he state of the stack aher each of these push operations.

M

uh a

Figure 18-2

5 puSh(5);

push(10) ;

t:J~50

push(15);

I; I

The pop operation retrieves (and hence, removes) a value from the stack. Suppose we execute three consecutive pop operations on the stack shown in Figure 18-2. FiJ:!;urc 18-3 depicts the results.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1069

us uf

i

18.1 Introduction to the Stack AbT

Figure 18-3 15

5

10

pop(x);

5

pop(x);

pop(x);

Yo

5

10

As you can see from Figure 18-3, the last pop operation leaves the stack empty.

Ri

az

For a static stack (o ne with a fixed size), we wil l need a Boolean isFu ll operation. T he isFull opera tion returns true if the staek is full, and fa l se otherwise. T his operation is necessary to prevent a stack overflow in the event that a push operation is attemp~ed when all the stack's elements have values stored in them. f or both static and dyna mic stacks we will need a boolea n iSEmpty operat\on. The iSEmpty operation returns true when the stack is empty, and false otherwise. This prevents an ereor from occurring when a pop operation is attempted on an empty stack.

A Static Stack Class

an

I

ss

Now we examine a class, I ntStack, that stores a static stack of integers and perfhrms the i sFull and isEmpty operations. The class has the member variables described in Table 18-1.

Ha

Table 18-1 Member Variable stackArray

top

An imeger that is used to mark the rop o f the stack.

m

ad

stackSize

Description A pointer to into When the conStructor is executed, it uses stackArra y ro dynamical ly allocate an array for sto rage. An imeger that holds the size of the stack.

T he class's member functions are listed in Table 18-2.

m

Table 18-2

uh a

Member Fun ctions

Descript ion I

T he cl ass constructor accepts an imeger argumem that specifies the siz~ of the stack. An integer array of th is size is dynamica ll y allocated, and assigned to stackArray. Also, rhe variable top is initialized to-l.

Destructor isFull

T he destr uctor frees the memory that was allocated by the constructor. Returns true if the stack is full and false otherwise. The staek is full when top is equal (0 stackSize-1Returns true if the stack is empty, and false otherwise. T he stack is empty when top is set to -1.

M

Constructo r

iSEmpty

(table continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1010

Table 18-2

(continued)

Member Functions

Description The pop function uses an integer reference parameter. The value at the top of the srack is removed and copied into rhe reference parameter.

Yo

pop

push

The push function accepts an integer argument. wh ich is pushed OntO the top of the stack. NOTE: Even though the constructor dynamica ll y alloca tes the stack array. it is still a static stack. The size of the stack does nOt change once it is allocated.

az

()

us uf

i

Chapter 18 Stacks and Queues

~----------------------~

Ri

The code fo r the class follows.

Contents of IntStac:k. h

II Specification file for the IntStack class 8ifndef INTSTACK H ,define INTSTACK H

3 4 5

class IntStack

6 7

i nt top;

II Pointer to the stack array II The stack size II Indicates the top of the stack

Ha

10

ss

private: int *stackArray; int stackSizei

8 9

an

1

2

11

public : II Constructor IntStack(int);

12

13 14 15

II Copy constructor I ntStack(const IntStack &);

ad

16 17

18 19

II Destructor -IntStaCk();

m

20

21

22

m

23

24 25

uh a

26 27 28

II Stack operations void push(int); void pop{int &J; bool iSFull() const ; bool isEmpty() const;

};

'endif

M

Contents of IntStack. Cpp 1

2 3 4 5

II Implementation fil e for the IntStack class 'include <iostream> 'include "IntStack.h" using names pace std ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

//***********************************************

7

II Constructor • // This constructor creates an empty stack. The * II size parameter is the size of the stack. * 1/***********************************************

9

10 12

IntStack :: lntStack(int size)

13 14

{

15 16

Yo

11

stackArray = new int[size]i stackSize = size; top :z -1;

}

20 21

II Copy constructor • 11***********************************************

az

17 18 19

//***********************************************

Ri

22

23

IntStack: : lntStack(const IntStack &obj)

2.

{

1/ Create the stack array . if (obj.stackSize > 0) stackArray new intlobj.stackSize]: else stackArray = NULL;

25 26

an

27 28 29

30

II Copy the stackSize attribute. stackSize = obj . stackSize;

ss

31 32 33

// Copy the stack contents. for (int count = 0; count < stackSizei count++) stackArray[count] = obj.stackArraY[Count]i

Ha

34 35 36 37 38

41

/1 Set the top of the stack . top = obj . top: }

ad

39 40

42

//***********************************************

"

// Destructor

44 45

//***********************************************

46

IntStack;:-lntStack()

m m 47

{

delete [J stackArraYi

48

49 50

}

51 52 53

//*************************************************

54

//*************************************************

uh a M

us uf

6 8

// Member function pUSh puShes the argument onto )) the stack.

* *

55

56

void IntStack :: push(int num)

57

{

sa

if (iSFull(»

59

{

cout «

60 61

1071

i

, 8.1 Introduction to the Stack A[Jn

"The stack is full. \n":

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 18

Stacks and Queues

62

else

63

{

top++; stackArray{topj

64

Yo

)

11*··**·*····****··· ··*** *·***··*****·**·************* II Member function pop pops the value at the top * II of the stack off, and copies it into the variable * II passed as an argument. • void Int5tack : :pop(int &num) {

77

if (isEmpty()) { cout « "The stack is empty . \n" ; } else

Ri

78 79

80 81 82

{

83

B.

85

91

}

ss

}

II~*******·******************************************

II Member function isFull returns true if the stack * II is fu l l, or false otherwise. • 11··************** -***** **-*·_··***·*···*··*·· - *···**

92

,. 93

num = stackArray[top]i top--;

Ha

86 87 88 89 90

bool IntStack::isFull() canst {

bool statuS;

ad

95

96 97

if (top == stackSize - 1)

status else status

98

true;

m

99

100

'0 ,

m

102 103

'0'

false;

return status;

}

108

//* ** ************************************************* // Member funciton isEmpty returns true if the stack * /f is empty, or false otherwise. * fl*--**·***** *-**-*·********* *************--*******-**

109 110

bool IntStack::isEmpty() canst

III

{

uh a

105

106 10 7

M

num;

az

71 72 73 74 75 76

=

)

an

65 66 67 68 69 70

us uf

i

1072

112

bool status;

113 114 115

if (top

=-

status

=

-1) true;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

18.1 Introduction to the Stack Apr

116

else

status

117

us uf

i

1073

= false;

U8

119 120

return status; }

Yo

The c1~ss has two conStructors, one that accepts an argument for [he stack size (tines 12 rhrou h 17 of I.ntStack . cpp) and a copy co~str~ctor ( li~~s. 2~ through 40). T he hrst construct9 r dynamica lly a llocates the stack array mime 14, lnltla llzes the stackSize lmember

9

Progr ~m

Ri

az

variable in line 15, and initializes the top member variable in line 16. Remember [~at items are st9red to and retrieved from the top of the stack. hl t his class, t he top of the stacf is actuaJly the end of the array. The variable top is used to mark the rap of the stack by holding the subscr~pt of the. last e1e~ent. When top ~olds -~, it indicates that the st~ck is empry!f(s~e the iSEmp~ y func tion, whIch returns true If top IS -1, or false otherw ise.) The sta k IS full when top is at the maximum subscri pt, which is stackSize - 1. This is the v lue that iSFu ~l tests for. It returns true if t he stack is full, or false otherwise. 18-1 is a si mple d river that demonsuates the IntStack class.

Program 18-1

an

II This Pl~gram demonstrates the IntStack class . iinclude <f ostrearn> iinclude "~ntStack . h" using name,s pace std;

ss

1 2 3

5

int main() 1

7

{

8

9 10 11

Ha

6

int cat;c hVar; I I To hold values popped off the stack I I Defiin e a stack object to hold 5 values . IntStac,k stack(5);

l2

16 11 18

19

20

N

;

stack,p~ Sh(15);

cout «~I "Pushing 20\n" ; stack. p'u sh (20) ; cout « "Pushing 25\ n "; stack.push(2S);

uh a

21 22 23

<i"

ad

tS

II Pushl the values 5, 10, 15, 20 , a nd 25 onto the stack. cout Pushing 5 \n" ; stack ' P .sh(S); I cout « i "Pushing 10\n" ; stack . PlllSh (10) ; cout « "pushin9 l S\n

m

I.

m

l3

24

25

M

26 27 28 29 30 31 32

II Pop the values off the stack. cout« "Popp i ng , •. \n M

;

stack , ~op(catchVar) ;

cout « catchVar « end1; stack . pop(catchVar); cout <d catchVar « end1; stack . p,op(catchVar); cout « . catchVar « endl; (program conrinues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 18

Stacks and Queues

Program lB-l

stack . pop(catchVar); cout « catchVar « endl ; stack . pop(catchVar); cout « catchVar « end1; return 0 ;

36 37 38

(continved)

Yo

)) 34 35

us uf

i

1074

}

Program Output

Ri

az

Pushing 5 pushing 10 Pushing 15 pushing 20 Pushing 25 Popping ... 25 20 15

10

an

5

ss

In Program 18-1, the constructor is ca lled with the argument 5. This sets up the member variables as show n in Figure 18-4. Because top is set to -1, the stack is empty.

Ha

Figure 18-4

[0]

stackArray -

top

[D

stackSize

0

[ I]

[ '] [ 3]

ad

[ 4]

M

uh a

m

Figure 18-5

m

Figure 18-5 shows the state of the member va riables after the push funct ion is called the first time (with 5 as its argument). The top of the stack is now at element o.

SlackArray -

5

(0 1

lop

~

stackSize

0

[ I]

[2] [3] [ 4]

Figure 18-6 shows the state of the member variables after all fi ve ca lls to the push function. Now the top of the stack is at element 4, and the stack is full.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

A7T

1075

figure 18路6 stackArray _

5 [0 1

top

0

slackSize

0

10 [1 J 15 [2 J

Yo

20 [3 J

us uf

i

18.1 Introduction to the Stack

25 [4]

Figure 18-7 stackArray -

5 [0 1 10 [1 J

top

Ri

az

Notice that the pop function uses a reference parameter, nurn. T he value that is popped off the stack is copied into nurn so it can be used later in the program. Figure 18-7 depicts the stare of the class members, and the nurn parameter, just after the first value is popped off the stack.

0

stackSize

[I]

1251-

20 [3J 25 [4]

ss

num

an

15 [2 J

Ha

The program continues to call the pop fuction until all the val ues have been retrieJ ed from the stack.

Implementing Other Stack Operations

m

ad

Morc complex operations may be built on the basic stack class previously shown. In [his section, we will discuss a class, MathStack, that is derived from Intstabk. , The MathStack class has two member functions: add() and sub{). The add{) function pops the first twO values off the stack, adds them together, and pushes the sum ontO the , stack. The sub() function pOpS the first twO values off rhe stack, subtracts the second value from the first, and then pushes the difference onto the stack. The class declaration is as fdHows.

m

Contents of MathStack . h II Specification file for the MathStack class 'ifndef MATH STACK H

6 7 8

class MathStack : public IntStack

M

uh a

1 2 3 4 5

9

10 11

'define MATH STACK H

'include 路'IntStack.h"

{ public: II Constructor MathStack(int s)

IntStack (s) {}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1076

Stacks and Queues

II MathStack operations

12 1J 14

void add(); void sub(); );

'endif

The definirions of rhe member funcrjons are shown

Contents of MathStack . cpp 1 II Implementation file for the

6 7

B

11············································*·· /1 Member function add . add pops * II the first two values off the stack and • /1 adds them. The sum i s pushed onto the stack . •

11·····*···········**·········.······· ••• ··•·····

9 10

void MathStack : : add()

11

{

12

an

int num, sum;

13 14 15 16

1/ Pop the first two values off the stack.

pop(num);

ss

pop( sum) i

17

18

II Add the two values, store in sum.

19 20

sum

21 22 23 24

// Push sum back onto the stack. push(sum);

28

1/ Member function SUb . sub pops the II first two values off the et~ck . The II second value is subtracted from the II first value. The difference is pushed II onto the stack.

m

2.

num;

ad

27

+~

Ha

)

25

2.

cl~ss

az

4 5

M~t h Stack

'include "MathStack . h"

Ri

2 3

here~

Yo

15 16

us uf

i

Chapter 18

30

• • • •

uh am

31 32

33 34 35

void MathStack : :sub() {

3. 37 38

M

39

int num , diff;

// pop the first two values off the stack . pOp{diff), pop(num);

40

41 42

// Subtract num from diff. diff - ~ num;

43

II Push diff back onto the BtdCk . push(diff);

44 45 46

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

us uf

The class is demonstrated in Program 18-2, a simple driver.

Program 18-2 II This program demonstrates the MathStack class .

'include <iostream> hnclude "MathStack.h" using names pace std;

5 6 7

iot ma i n() (

8

int catchVar;

Yo

1 2 3 4

II To hold values popped off the stack

az

9

II Create a MathStack object. MathStack stack(5);

10 11

II Push 3 and 6 onto the stack . cout « "Pushing 3\0" ; stack.push(3)i

16 17

cout «

"19

an

"Pushing 6\0"; stack . push(6) i II Add t he two values. stack. add();

20

Ri

12

13 14 15

21

/1 Pop t he sum off the stack and display it . cout « "The sum is ";

24

stack . pop(catchVar)i cout « catchVar « endl «

ss

22 23

II Push 7 and 10 onto the stack

cout «

"pushing 7\0" ; stack . push( 7) ; cout « ·'Pushing 10\ n"; stack . push(lO);

ad

30 31 32

33

II Subtract 7 from 10 . stack.sub();

m

34 35 36 37 3S 39 40

II Pop the difference off the stack and display it . cout « '·The difference is "i

)

m

stack . pop(catchVar)i cout « catchVar « endli return 0;

uh a

41

endl;

Ha

25 26 27 28 29

1077

i

, 18.1 Introduction to the Stack AOT

Program Output pushing 3

M

pushing 6 The sum is 9

Pushing 7 Pushing 10 The difference is 3

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 18 StoCk5 and Queues

i

lOlIJ

us uf

It will be left as a Programming ChalJengc for you to implement the multI), div(), and mod () functions that will complete the Ma thStack class.

Stack Templates

Yo

The stack classes shown in this chapter work on ly with integers. A stack template can be easily designed to work wIth any data type. This, too, will be left as a Programming Challenge for you [Q complete.

az

Dynamic Stacks each push or pop operation.

Ri

CONCEPT: A stack may be impl em ented as a linked list, and expand o r shrink with

A dynamic stack is built on a link ed list instead of a n aHay. A linked list-based stack offers twO advantages over an array-based stack. First, there is no need to specify the sta rting

an

size o f the stack. A dynamic stack simply startS as an empty linked list, then expands by one node each time a value is pushed. Second, a dynamic stack w ill never be full, as long as the system has enough free memory.

Ha

ss

In this section we will look at a d ynamic stack class, DynlntStack. This class is a dynamic version of the IntStack class previously discussed. The class decla ration is s hown here:

Contents of Dynlnt.St.ack. h

5 6 7

class DynlntStack {

private : II Structure for stack nodes struct StackNode

m

8 9

II Specification file for the DynlntStack class 'ifndef DYNINTSTACK H ' define DYNINTSTACK H

ad

1

2 3 4

{

m

10 11

12

uh a

13 14

15

int v alue;

StackNode *nexti

II Value in the node II Pointer to the next node

};

StackNode *toPi

II Pointer to the stack t op

16 17

M

18 19

20

public: II Constructor DynlntStack() { top'" NULL; }

21

22 23

II Destructor -DynlntStack();

" To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1079

18.2 Dynamic Stacks

28 29

),

30

'endif

i

II Stack operations void push(int): void pop(int &); bool isErnptY()i

us uf

25 26 27

empty.

az

The definitons of the other member functions are shown here:

1

'include <iostream> finclude "DynIntStack . h" using namespace std;

4

Ri

Contents of DynlntStack . cpp 2 3

Yo

The StackNode structure is the data type of each node in the linked list. Tt has a value member and a next pointer. Notice that instead of a head pointer, a top pointer is d efined . This member will always point to the first node in the list, whidl will represent the top of the stack. It is initialized ro NULL by the conStructor, to signify that the stack is

5 6 7

11********·*·*·*************************************

8

11***************··******··*·*··_*-***·********-****

an

II Destructor II This function deletes every node in the list.

9

OynIntStaek ,, - OynIntStack() {

ss

10 11

12

StackNode *nodePtr, *nextNode;

13

II position nodePtr at the top of the staCK. nodePtr = top ;

Ha

14 15

16 17 18

II Traverse the list deleting each node. while (nodePtr != NULL ) { nextNode = nodePtr->next; delete nodeptr; nodePtr = nextNode;

ad

19 20 21 22

)

m

23 24

* -

)

25

11*********_·**·*********--*********************** II Member function push pushes the argument onto * I I the stack. * 11************************************************

m

26 27

uh a

28 29

30 31 32 33

void DynIntStack :: push(int num) { StackNode *newNodei II Pointer to a new node

M

3' 35

36 37 38

II Allocate a new node and store num there. newNode - new StackNode ; newNode - >va1ue = num;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Stacks and Queues

1/ If there are no nodes in the list 1/ make newNodc the first node. if (isEmpty(» (

43

top

44 45

newNode->next )

46

else

47 48

{

49 50 51 52

=

newNode;

= NULL;

II Otherwise, insert NewNode before top .

newNode->next = top;

top

i

39 40 41 42

us uf

Chapter 18

Yo

1080

= newNode;

)

)

53 11--·-*·_···_·_--_······_-_·_·_----_·_·_-------_·_·_·-

II Member function pop pops the value at the top * II of the stack off , and copies it into the variable * II passed as an argument. *

az

54 55 56

Ri

57 11-._.---_._· __ ._._---_._ ....... _-------_._._----_·_-58 59

void OynlntStack::pop(int &nurn)

60 61

(

StackNode -temp; II Temporary pointer

an

62

63

1/ First make sure the stack isn't empty .

64

if (iSEmpty(»

65

{ caut«

"The stack is empty . \n";

ss

66

67

else (

70

num

top->value;

)

)

76

ad

74

ff Member function isEmpty returns true if the stack· ff is empty, or false otherwise. • ff····················································

m

78 79

=

temp = top->next; delete top ; top = temp ;

71 72 73 75

II pop value off top of stack

Ha

68 69

booIDynlntStack : : isEmpty()

83

(

m

80 81 82

bool status;

96

i f ( ! top)

87 88 89 90 91

status true; else status"" false ;

M

uh a

84 85

return status ;

92

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

S ta~ks

1081

i

18.2 Dynamic

us uf

Let's look at the push operation in lines 31 thro ugh 51 of DynlntStack . cpp. First, in lines 36 and 37, a new node is al located in memory and the fu nction argumenr i~ copied into its value member: ' newNode = new StackNodei newNode->value = num;

Yo

Nex t in line 41, an i f statement calls the isEmpty funct ion to determine whether the stack is empty: if (isEmpty ( ) ) top = newNode i newNode->next = NULL ;

az

{

}

If is Empty returns false

111

Ri

rf isEmpty returns t r ue, top is made to poin t at the new node, and the new nod.e's next pointer is set to NU LL. After these sta temcnrs execute, there will be one node i~ the list (a nd one value on the stack). the if statement, the fo llowing statements

III

lines 46

else

an

through 50 are executed. II Otherwise, insert newNode before top

{

ss

newNode - >next z top ; top = newNode; }

Ha

Notice that newNode is being inserted in the list before the node that top pOintSlto. T he top pointer is then updated to pai ne to the new node. When this is done, newNode is at the top of rhe stack.

(isEmpty{))

m

if {

ad

Now let's look at the pop function in lines 59 through 75. Just as [he push functipn must insert. nodes at the head. of. the list, pop mu~t delete nodes at the head of the. list. ~ i rst, the fu nctIon calls isEmpty In Ime 64 to determme whether there are any nodes 10 the stack. If there are none, a n error message is displayed:

cout ÂŤ

"The

stack is empty . \n" ;

}

iSEmpty returns false, then the following statements in lines 68 th rough 74 are e:kecured.

m [f

else

II pop value off top of stack

uh a

{

num = top- >value ; temp - top- >next ; delete top; top = tempi

M

}

Fi rst, the value member of the top node is copied into the num reference paramcl:er. This saves (he val u ~ for la tet use in the program . Next, a tempo.rary St~ckN~de point1r, temp, is made to pomt to top- >next. If there are other nodes III the list, th iS causes ~emp to poim ro the second node. (If there are no more nodes, this will caus~ temp to point [0 NU LL.) Now it is safe to delete the top node. After the cop node IS deleted, the top

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter' B Stacks and Queues

i

1082

us uf

poimer is sec equal CO temp. This action moves the top pointer down the JiSt by one node. The node that was previously second in the list becomes first.

The isEmpty function) in lines 82 through 92, is simple. If top is NULL, then the list (the stack) is empty.

Yo

Program 18-3 is a driver that demonstra tes the DynlntStack class.

5

. 6 7

9 10 11

II This program demonstrates the dynamic stack. 1/ class DynlntClass. 'include <iostream> 'include "DynlntStack.h" using namespace std;

int main() { int catchVar;

Ri

1 2 3 4

1/ To hold va lues popped off the stack

II Create a DynlntStack object. DynlntStack staCk;

an

12

az

Program 18-3

13

II Push 5, 10, and 15 onto the stack. cout « "Pushing 5\n": stack.push(5); cout « "pushing 10\n"; stack . push(10); cout « "Pushing 15\n"; stack.push(15);

22

II Pop the va lues off the stack and display them. cout« "Papping ... \n"; stack.pop(catchVar)i cout « catchVar « endl; stack . pop(catchVar): cout « catchVar « end1: stack . pop(catchVar); cout « catchVar « endl;

Ha

ss

14 15 16 17 18 19 20 21 23

24

m

ad

25 26 27 28 29 30 31

33 34 }

uh a

35

m

II Try to pop another value off the stack. cout« "\nAttempting to pop again ... "i stack.pop(catchVar): return 0;

32

Program Output

M

pushing 5 Pushing 1 0 pushing 15 Popping ... 15 10 5

Attempting to pop again ... The stack is empty.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1083

us uf

i

, 8.3 The STL stack Conta iner

The STL stack Container

CONCEPT: The Srandard Template Library offers a stack template, whi ch m a~ be

Yo

implemented as a vector, a list , or a deque.

Storing Objeus in ~n STL " t.ack

az

So far, the 5TL contai ners you have learned about are vectors and lists. The ST~ stack container may be implemented as a vector or a list. (It may also be implemented as a deque, which you will lea rn abo ut later in this chapter.) Because the stack contai ner is used to adapt th ese othe r containers, it is often referred to as a container adapter. Here are examp les of how to define a stack of i nts, implemented as a vector ' Ia list, and a deque .

II Vector s tack II List stac k II Default - deque stack

Ri

s tack< int, vector <int> > iStack; stack< int , list<int> > iStack; stack< int > iStack;

ss

an

NOTE: Be sure to pur spaces between the angled brackets that appea r next to e~ch other. This wi ll prevent the compiler from mistaking> > for the stream extractio1n operatOr, ».

Table 18-3 lists and describes some of the stack template'S member func tions.

Ha

T.ble 18-3 Member Function empty

ad

Examples and Description if (myStack.empty(» The empty member function returns true if the stack is empty. If the stack has elements, it returns false . myStack . pop() ; T he pop functio n removes the element at the top of the stack. myStack. pus h (x l ; The push function pushes an element with the va lue x onto the stack. cout « myStack . siz e () « endl; The size function returns the number of elements in the list.

size

x

uh a

top

m

push

m

pop

~

==

myStack . top() ,

T he top function returns a reference to the element at the top of the stac~.

NOTE : T he pop fu nction in the stack template does nOt retrieve the va lue fro m the top

M

~ L-_o_f_t_h_,_,_t_ac_k_,_i_t_o_n_l_y_,_e_m_o_v_e_'_i_t._T _o__,_,t_,_ie_,_e_t_h_e_v_._I_"_,_,_y_o_"_,_n_"_,_t_C._I_I_t_h_c_t_o_p_f_"_n_c_t~\o_n__fi_,,_t_. ..J Program 1 8-4 is a driver tha t demonstrates an ST L stac k implemented as a vectpr.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 18 Stacks and Queues

1/ This program demonstrates the STL stack II container adapter.

3 4 5 6 7

' include <iostream> 'include <vector> 'include <stack> using namespace std;

.

Yo

1 2

us uf

i

1084

S int main() {

II Max value to store in the stack II Loop counter

canst int MAX -

13

II Define an STL stack stack< int, vector<int> > iStack;

int count;

Ri

14 1S 16 17

,.

II Push values onto the stack. for (count = 2; count < MAXi count +- 2) { cout « "Pushing n « count « endl;

19 20 21

an

iStack.push(count); }

22 23 24

Ha

ss

1/ Display the size of the stack . cout « MThe size of the stack is M; cout « i Stack,size() « endl;

2S 26

/1 Pop the values off the stack .

27

2. 2.

for (count - 2; cou n t < MAX; count + - 2) {

cout «

30

"popping

iStack.pop() ;

31

32

«

iStack . top() «

endl;

ad

}

return 0; }

Program Output Pushing 2 pushing 4

m

33 34

az

H;

10 11 12

uh am

Pushing 6 The size of the stack is 3 popping 6 popping 4 Popping 2

M

~

Checkpoint

18.1 18.2

Describe what UFO means. What is the difference between static and dynamic stacks? What advantages do dynamic stacks have over static stacks?

18.3

What are the two primary stack operations? Describe them both.

18.4

What STL types does the STL stack container adapt?

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

,

1085

us uf

i

18.4 Introduction to the Queue AOT

Introduction to the Queue ADT

Yo

CONCEPT: A queue is a data structure that stores and retrieves items in a first-io~ first-out manner.

Definition

Like a stack, a queue (pronounced " cue") is a data structure th at holds a scquenGe of elements. A queu e, however, pro vides access to its elements in first-hl, first-oHt (F1F<tÂť order.

Ri

az

The ele ments in a qlleue are processed like Custo mers sta nding in a grocery c hcckjout li ne: The first CUStomer in line is the first o ne served .

Application of Queues

an

Queue data structures are commonly used in computer operating systems. They ~re especially important in multiuser/m ultitasking envi ronments where several users or ri ,sks may be requesting the same resource simulta neously. Printing, for example, is controlled by a queue because only one document may be printed at a time. A queue is used to hold print jobs su bmitted by users of the system, while the priorer services those jobs one at a time.

Ha

ss

Communications soft ware also uses queues to hold data rece ived over networks f nd dialup connections. Sometimes data is transmitted ro a system faste r than it ca n be pnocessed, so it is placed in a queue when it is received.

Static and Dynamic Queues

ad

Just as stacks are implemen ted as arrays or Imked lists, so are queues . Dyna mic queues offer the sa me advantages over static queues that dynamic stacks o ffe r over statib stacks. In fact, the primary difference between queues and stacks is the way data ele~enrs are accessed in each structure.

m

Queue Operations

m

Just like check-our lines in a grocery store, think of queues as having a front and a rea r. T his is illustrated in Figure 18-8.

M

uh a

Figure 18-8

When an element is added to a queue, it is added ro the rear. When an element is removed from a queue, it is removed from the front . The twO primary queue operations are enqueuing and dequeuing. To enq ueue means to insert an element at the fear of a queu e,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1086

us uf

i

Chapter 18 Stacks and Queues

and to dequeue means to remove a n element from the front of a queue. There are several different algorithms for implementing these operations. We w ill begi n by looking at the most simple.

of

Yo

Suppose we have a n empty static integer queue that is capable of ho lding a maximum three values. With that queue we execute rhe following enqueue operations. enqueue ( 3) ;

enqueue ( 6 ) i enqueue ( 9 ) ;

Figure 18-9 illustrates the state of the queue after each of these enqueue operatio ns.

az

Figure 18-9

Ri

enqueue(3);

enqueue(6) ;

an

FILL

ss

~ enqueue(9);

Ha

"~"

~

M

uh a

m

Figure 18-10

m

ad

Notice in this example rhar the front index (which is a variable holding a subscript or perhaps a pointer) always references the same phys ical element The rea r index moves fo rward in the arr ay as items are enqueued. Now let's see how dequeue operations are performed. Figure 18-10 illustrates the sta re of the queue after each of three consecutive dequeue opera tions.

dequeue{) ;

'trEfj dequeue();

"tiIJ dequeue(); Flonl .. -1

Real ~- 1

II II To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1087

i

, 8.4 Introd uction to the Queue AElT

us uf

In the dequeuing operation, the element at the front of the queue is removed. This is done by moving all the elements after it forward by one position. After the first dequeJ e operation, the value 3 is removed from the queue and the value 6 is at the from. Afterl the second dequeue operation, the value 6 is removed and the value 9 is at the front. No1tice cha t when only one value is stored in the queue, that value is at both the front and rhelrear.

Yo

When the last dequeue operation is performed in Figure 18-10, the queue is empty. An empty queue can be signified by sening both front and rear indices to -1.

az

The problem with this algorithm is its inefficiency. Each time an item is deque,lled, the remai ning items in the queue are copied fo rward to their neighboring element. 'ij-te more items there are in the queue, the longer each successive dequeue operation will take.

Ri

Here is one way to overcome the problem: Make both the front and rear indices move in the array. As before, when an item is enqueued, the rcar Index is moved to make tpom for it. But in [his design, when an item is dequeued, the from index moves by one element toward the rear of the queue. This logically removes the from item from the qJeue and elimi nates the need to copy the remaining items to their neighbori ng elements.

,

an

With th is approach, as items are added and removed, the queue gradually i crawls" towa rd the end of the array. This is illustrated in Figure 18-11. T he shaded squares represent the queue elements (between the fron t and rear).

ss

Figure 18-11

ad

Ha

I. I

m

m

The problem with th is approach is that the rear index cannot move beyond the last element in the array. The solution is to think of the array as ci rcular instead of lindr. When an item moves past the end of a circular array. it simply "wraps arou nd " to the be~i nn ing. For example, consider the queue depicted in Figur e 18- 12.

M

uh a

Figure 18路12

rear'" 8 fronl ,= 5

T he value 3 is at the rear of the queue, and the value 7 is at the front of the queJe . Now, suppose an enqueue operation is performed, inserting the value 4 into the queu' . Figure 18-13 shows how the rear of the queue wraps around to the beginning of the array.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1088

us uf

i

Chapter 18 Stacks and Queues

Figure 18-13

141 (01

171 916131

[lJ

{2]

(3]

[41

[5]

(61

{7]

[8]

Yo

rear ::: 0 front = 5

So, what is the code for wrapping the rear marker around to the opposite end of the array? One straightforward aproach is to use an if statement such as ~-

queueS ize - 1)

az

if (rear

rear'" 0; else

Another approach is with mo d ular arithmetic:

rear::: (rear +

1) %

queueSize;

Ri

rear++;

an

This scatemenr uses the % operator to adjust the va lue in rear to the proper position. Although this app roach appears more elegant, the choice of which code to use is you rs.

ss

Detecting Full and Empty Queues with Circular Arrays

Ha

One problem with the circula r arra y algorithm is that, because both the fro nt and rear indices move through the array, detecting whether the queue is full or empty is a challenge_ When the rear index and the front index reference the same element, does it indicate that o nly one item is in the queue, or that the queue is full? A number of approaches are commonly taken, two of which are listed be low. When moving the rear index backward, always leave one element empty between it and (he from index. The queue is full when the rear index is within two posi-

ad

â&#x20AC;˘

tions of the front index.

â&#x20AC;˘

Use a counter variable

to

keep a rota I of the number of items in the queue.

m

m

Because it might be helpful to keep a count of items in the queue anyway, we will use the second method in our imp lementation.

A Static Queue Class

uh a

The decla ration o f [he IntQueue class is as follows:

M

Contents of IntQueue. h 1 2 3

,

II Specification file for the I ntQueue class fif nd ef INTQUEUE_H #define INTQUEUE_H

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

18.4 Introduction to the Queue A~T

i

(

7

private: int *queueArray; int queueSizei int front; int rear; int numItems; public: II Constructor IntQueue(int);

a 9 10

11 12 13 14

15 16 17 19

II Points to /I The queue II Subscript II Subscript /I Number of

the queue array

size

us uf

class IntQueue

6

of the queue front of the queue rear items in the queue

Yo

5

1089

IntQueue(const IntQueue &);

20

II Destructor -IntQueue();

21 22 23 24

25 26

boal isFull() canst; void clear(); };

30

'endif

ss

27 29 29

an

II Queue operations void enqueue(int); void dequeue(int &); bool isErnpty{) canst;

Ri

19

az

II Copy constructor

Notice that in addition to the operations discussed in this section, the class also dbclares a

Ha

member function named clear. This function clears the queue by resetting the f~ont and rear indices, and setting the numltems membe r to O. The member function definitions are

listed below.

Contents of IntQue ue. cpp

ad

II Implementation file for the IntQueue class

'include <iostream> linclude" IntQueue. h" using namespace stdj

m

1 2 3 4

5 6

m

7

8 9

uh a

10

11

IntQueue::lntQueue(int s) (

M

12 13 14

queueArray = new int[s); queueSize ~ Sj front = -I,

15

rear -

16

numltems - 0;

17 18

-1;

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Stacks and Queues

i

Chapter 18

//*************************************************************** II Copy constructor • II*************************************************.~.*~*~**~WW~*

24

{

IntQueue :: IntQueue(const IntQueue &obj)

25

II Allocate the queue array. queueArray = new int[obj.queueSizej;

26 27

2'

II Copy the other object's attributes. queueSize = obj.queueSize; front a obj . front; rear = obj . rear; numItems = obj.numItems;

29

az

30 31 32

33 34 35

Ri

II Copy the other object's queue array. for (int count = 0; count < obj . queueSize; count++) queueArray[countj = obj.queueArray[Countj;

36 37

us uf

19 20 21 22 23

Yo

1090

)

38

39

II*******************~**************** * *************** ***********

'0

II Destructor /1**************************************************** *********** IntQueue::-IntQueue() {

45

"

48

49 50

delete [] queueArraYi )

Ha

46

an

44

ss

41 42 43

,

//*************************************************************** // Function enqueue inserts a value at the rear of the queue . * 11**************************************************** ***********

51

54

55 56

void IntQueue :: enqueue(int num) { i f ( isFull ( ) ) cout « "The queue is full. \n"; else

ad

52 53

{

m

57

m

58 59 60 61

uh a

62 63 64

65

1/ Calculate the new rear position rear = (rear + 1) % queueSize; 1/ Insert new item queueArray[rearj = nurn; 1/ Update item count numltems++;

) )

66

67

M

68

69 70

1/******************* ********** *********************** *********** II Function dequeue removes the value at the front of the queue * // and copies t into num. * 11************************* ** ************************* *~~********

71

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

, 8.4 Introduction to the Queue ADT

{

i f (isEmpty(» cout « "The queue is empty . \n"; else

74 75

76 77

II Move front front = (front + 1) % queueSizei II Retrieve the fron t item num = queueArray[front!i II update item count numltems -- ;

80 81 82

83

"

az

)

8S

86

89

11 •• * · **·**********···**·****·*··*··*******··***·*·*** *. ~ * •••• *** II isEmpty returns true if the queue is empty, otherwise l false. * 11**·**···**·****·**·*···******····*·*··***····*·***** * •• ********

Ri

88 90

91

bool IntQueue : :isEmpty() canst

92 93

{

if (numltemS ) status = false; else status = true;

96

ss

97 98 99

Ha

,

//*****************************************************~***~****

I I isFull returns true i f the queue is full, otherwise flalse . II~~*******·******************************~*********** *~***

*

•• ***

bool I ntQueue : :isFUll{) const { bool status;

m

10' 105 106 107 108 109

return status; )

ad

1 02 1 03

an

bool status;

"95 100 101

Yo

{

78 79

87

i

void IntQueue::dequeue(int &num)

73

us uf

72

109 1

110

if (numltems < queueSize) status falsei else status = true;

111

112

uh a

m

113 11 4 115 116 117

return status; }

M

118

• • *****.******~***************** ••• *** **~.*******.

119

II*~******.*~***

120

1/ clear sets the front and rear indices, and sets numlte~s to O. •

121

/1* *************************************************** ************

122

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

void IntQueue :: clear() (

125 126 127

front = queueSize - 1 ; = queuesize - 1;

r ear

numItems

= 0;

)

Program 18·5

IS

a driver that demonstrates the IntQueue class.

6

7

, 8

/1 This program demonstrates the I ntQueue class. finclude <iostream> Unclude " I ntQueue .h" using namespace std ; int main() ( canst i o t MAX_VALUES = 5 ;

II Max number of values

II Create an I ntQueue to hold the values. IntQueue iQueue(MAX_ VALUES);

10 11

an

12

II Enqueue a series of items . cout« "Enqueuing" «MAX_VALUES« for (int x = 0 ; x < MAX_ VALUES; x++) iQueue . enqueue(x) ;

13 14

" items .•. \n" ;

ss

15

"'

17 18

Ha

II Attempt to enqueue just one more item. cout « "Now attempting to enqueue again ... \n" ;

19 20

iQueue . enqueUe(MAX_VALUES)i

21

II Dequeue and retrieve all items in the queue cout « "The values in the queue were : \n" ; while (!iQueue. i sEmpty ( ) ) ( int value; iQueue . dequeue(va l ue) ; cout « value « endl ; ) return 0 ;

m

)

m

ad

22 23 24 25 26 27 28 29 30 31

Ri

1 2 3 4 5

az

Prog ram 18-5

Yo

128

us uf

123 124

i

Chapter 18 Stacks and Queues

1092

Program Out put

o I

M

2 3

uh a

Enqueuing 5 items .. . Now attempting to enqueue again .. . The queue is full . The values in the q ueue were :

4

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

18.5 Dynamic Queues

us uf

i

1093

Dynamic Queues

Yo

CONCEPT: A queue ma y be imp lem ented as a linked list, and expa nd or s h rj n ~ with each enqueue or dequeue operation.

Ri

az

Dynamic queues, which are bu ilt around linked lists, are much more intuitive tp understa nd tha n static queues. A dynamic que ue sta rts as an empty linked list. With the nrst enqueue operation, a node is added, which is pointed to by the front and rear f' ointers. As each new item is added to the que ue, a new node is added to the rear of the list, and the rear pointer is upda ted to point to the new node. As each item is deq ueued, ~he node pointed to by the front pointer is deleted, and front is made to point to tbe nex~ node in the list. Figure 18-14 shows the structure of a dynamic queue. Figure 18- 14

an

I & 1 [+ L I + NULL ~

ss

~ [iJ

Ha

fron t

[iJ rear

A dynamic imeger que ue class is listed here.

ad

Contents of Dy nlntQu e ue . h 'ifndef DYNINTQUEUE_H

2 3

'define DYNINTQUEUE_H

4

class DynlntQueue

5

{ private:

m

1

6

/1 Structure for the queue nodes struct QueueNode

9

{

m

7 8

int value; II Value in a node QueueNode *next; II Pointer to the next node

uh a

10 11

12

};

M

13

14

QueueNode *fr ont ;

II Tne tront of tne queue

15 16

QueueNode *rear ; int numltems ;

II The rear of t he queue

II Number o f i t ems in the queue

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Stacks and Queues

17 18

public : /1 Constructor

19 20 21

DynlntQueue(J ;

22

-oynlntQueue();

us uf

Chapter 18

1094

/1 Destructor

24 25

II Queue operations void enqueue(int);

26

void dequeue(int &);

27 28 29 30 31

bool isEmpty() canst; boo I iSFul 1 () canst; voi d clear();

'include <iostream> 'include "DyntntStack.h"

3

us i ng namespace std;

11*·············*·····························*····· / / Destructor * II This function deletes every node in the list. * li···*·* *·**··*····**···*·*·*·****·*·***************

ss

5

6 7 B

an

1 2

Ri

az

); lIendif

Contents of DynlntQueue. Cpp

4

Yo

23

DynlntStack :: -DynlntStack()

11

{

12

Ha

9 10

StackNode *noctePtr, *nextNode ;

13

II position nodePtr at the top of the stack. nodePtr = top;

16 17 18

/1 Traverse the list deleting each node . while (nodePtr J= NULL)

ad

14 15

{

m

19 20 21 22 23

}

m

24 25

nextNode = nodePtr- >next; delete nodePtr; nodePtr = nextNode;

uh a

26 II················································ 27 II Member function push pushes the argument onto · 28

II the stack.

29

//www**w«***«************************ ~ *********.**

M

30

31 32 33

void DynlntStack :: push(int num) { StackNode ·newNode; Pointer to a new node

II

34

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

,


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1095

I I Allocate a new node and store num there. newNode '" new StackNode; newNode- >value = num;

38

39

II

40

1/ make newNode the first node .

41

if (isEmpty())

42

{

Yo

If there are no nodes in the list

top = newNode; newNode->next '" NULL:

43

44 45

else {

48 49 SO

56 57

newNode->next '" top: top ~ newNode;

Ri

}

11**************************************************** II Member function pop pops the value at the top * II of the stack off, and copies it into the variable * II passed as an argument . 11****************************************************

an

51

52 53 54 55

/1 Otherwise, insert NewNode before top.

58

void DynlntStack :: pop(int &num)

60

StackNode *temp;

)

68

else

II

Pop v a lue off top of stack

ad

6'

70

Temporary pointer

II First make sure the stack isn't empty. if (iSEmpty() ( cout « "The stack is empty . \n";

64 65 66

{

m

71 72

II

Ha

61

62 63

69

ss

S9

az

46 47

us uf

35 36 31

i

18.5 Dynamic Queues

73

num = top- >value; temp'" top->next; delete top; top'" temp i

74

m

75

}

76 77

uh a

78

M

79

80 81 82 83 84 85

11************************ **************************** / I t-Iember function iSEmpty returns true if the stack * II is empty, or false otherwise. * 1/*********************************** * ****************

boolDynlntStack::isEmpty() { bool status i

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1096

if

87 88 8'

I \toP)

us uf

..

i

Chapter 18 Stacks and Queues

status = true;

else status = false;

90

"

)

Yo

92

return status;

Program 18·6 is a driver that demonstrates the OynlntQueue class.

, B

int main( ) { const int MAX_VALUES

10

az = 5;

II Create a DynlntQueue object . DynlntQueue iQueuej

11 12

1]

II Enqueue a series of numbers . cout « "Enqueuing" « MAX_VALUES « for tint x a OJ X <; 5; x++)

14

15

iQueue.engueU8(X)i

17

18

" items ••• \n" i

Ha

16

II Dequeue and retrieve all numbers in the queue cout « "The values in the queue were : \n "i

19 20

while (liQueue . isEmpty())

21

{

22

int value;

iQueue.dequeu8(value)i

24

cout « value « endl; ) return 0 ; )

m

25

ad

23

26 27

Ri

7

'include <iostream> Unclude "DynlntQueue.h" using names pace stdi

an

5 6

II This program demonstrates the DynlntQueue class .

ss

1 2 3

m

Program Output Enqueuing 5 items ...

The values in the queue were:

o

uh a

1

M

2 3 4

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

18.6 The STl deque and queue Containers

The STL deque and queue Containers

us uf

i

1097

Yo

CONCEPT: The Standard Template Library provides two containers, deque a~d queue, for implementing qu eue-like data structures.

az

In ch is section we will exa mine (w o ADTs offered by [he Standard Template Library: deque and queue. A deque (pronounced "deck" or "deek" ) is a double-ended ql\eue. It is si milar to a vector, but allows efficient access to va lues at both the front and the rear. The queue AOT is like the stack ADT: It is actually a contai ner adapter.

The deque Container

Ri

Think of the deque container as a vector that provides quick access to the elem'e nt at its front as wel l as at the back. (Like vector, deque also provides access to its elements with the [ I opera ror.)

ss

an

Programs tha t lise the deque ADT must include the deque header. Because we arct concentrating on its qu eue-like characteristics, we will focus our attention on the push back, pop_front, and front member funC[ions. Ta ble 18-4 describes them.

Member Function

Ha

Examples and Description iDeque . push_baCk()i Accepts as a n argument a va lue to be inserted into the deque . The argument is inserted after the last element. (Pushed OntO the back of the deque. ) iDeque .pop front(): Removes the-first element of the deque. c out ÂŤ iDeque.front() ÂŤ endl; front retu rns a reference to the fi rst element of the deque.

ad

pop_front

m

fr ont

Program 18-7 demonstrates the deque container.

m

Program 18-7 1

II This program demonstrate s the STL deque container .

2 3

5 b

int:. main {}

7

{

uh a 4

'include <iostream> tinclude <deque> using namespace stdi

M

B

9

10

canst i nt MAX lnt count:

= B;

II Max value Loop counter

II

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 18-7

Stac.ks and Queues

i

Chapter 18

(continued)

11

II Create a deque object .

12

deque<int> iDeque:

us uf

1.098

13

IS

16 17 18

Yo

II Enqueue a series of numbers. cout « "I will now enqueue items ... \n": for (count = 2: count < MAX; count += 2)

I.

{

cout « "pushi ng " « count « iDeque.push_ back(count};

19 20

endl:

)

21

cout « "Popping "« iDeque.pop_front()i

27 28

}

29

r eturn 0; )

Program Output I

endl:

an

30

iDeque . front() «

Ri

{

26

az

1/ Dequeue and display the numbe rs . cout « "I will now dequeue items ... \n": for (count = 2: count < MAX: count += 2)

22 23 2. 25

will now enqueue items ...

Ha

r will now dequeue items ... Popping 2 popping 4 Popping 6

ss

pusning 2 Pushing 4 Pushing 6

ad

The que ue Container Adapter

m

The insertion and removal operations supported by queue are the same as those supported by the stack ADT: p ush, pop, and top. There are differences in thei r behav ior, however. T he queue version of push always inserts an element a[ [he rear of the queue. The queue version of pop always removes an element from the structure's from. T he top function rerurns the value of the element at the fro nt of [he queue.

uh a

Storing Objects in an STt queue

m

The queue container adapter can be bu ilt upon vectors, lists, o r deques. By defa ult, it uses deque as its base.

M

Program 18-8 demonstra tes a queue. Because the defi nition of the queue does not specify which typc of container is bc:ing adapted, rhe queue wjli be built on a deque.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

18.6 The STL deque and queue Containeb

3

4

i

II This program demonstrates the STL queue contai ner adapter . 'include <i ostream> #include <queue> using namespace std; int main() {

const int MAX : 8; int count ;

8 9 10 11 12

II II

Max value Loop counter

II Define a queue object. queue<int> iQueue;

13

II Enqueue a series of numbers . cout « " I will now enqueue items . . . \n"; for (count = 2: count < MAXi count += 2) { cout « "Pushing "« count « endl ; iQueue.push(count) ;

14

Ri

15

16 17 18 19 20

an

)

21

II Dequeue and displ ay the numbers . cout « "I will now dequeue items ... \n"; for (count = 2: count < MAX; count += 2) {

27

2' 29

i Queue.front() «

endli

Ha

cout « "popping "« iQueue . pop ( ) :

26

ss

22 23 24 2S

30

az

6 7

Yo

S

us uf

Program 18-8 1 2

1099

return 0; )

M

uh a

m

m

ad

Program Output I will now enqueue items ... Pushing 2 Pushing 4 Pushing 6 I will now dequeue items ... Popping 2 Popping 4 Popping 6

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises Short Answer 1. What does LIFO mean? 2. What element is always retrieved from a stack?

4. Describe two operations tha t al l stacks perform.

5. Describe

twO

operations tha t static stacks must perform.

Yo

3. What is the difference between a static stack and a dynamic stack?

us uf

i

Chapter 18 Stacks and Queues

1100

6. The STL stack is considered a container adapter. What does that mean?

az

7. What types may the STL stack be based on ? By default, what type is an ST L stack

based on?

Ri

8. What does FIFO mean?

9. When an element is added to a queue, where is it added?

10. When an element is removed from a queue, where is it removed from? 11. Describe two operations tha t all queues perform.

an

12. What two queue-like containers does the ST L offer?

Fill-in-the-Blank

ss

13. The _ _ _ _ element saved onto a stack is the first one retrieved. 14. The two primary stack operations are _ _ _ _ and _ _ _ _.

Ha

15. _ _ _ _ stacks and queues are implemented as arrays.

16. _ _ _ _ stacks and queues are implemented as linked lists . 17. The STL stack container is an adapter for the _ _ _ _ _ _ _ _ â&#x20AC;˘ and _ _ _ _ STL containers.

element saved in a queue is the first one retr ieved .

ad

18. T he

19. T he two primary queue operations are

and _ _ __

m

20. The two ADTs in the Standard Template Library that exhibit queue-like behavior are _______ and _______

m

21. The queue ADT, by default, adapts the _ _ _ _ container.

Algorithm Workbench

uh a

22. Suppose the followi ng operations are performed on an empty stack: push(O) ;

push(9);

pUSh(12);

M

push(l);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1101

i

Review Questions and Exercises

us uf

Insert numbers in the foUow ing diagram to show what will be stored in the static stack after the operations above have executed. Top of Stack

Yo

f--------1 Bottom of Stack

az

23. Suppose the following operations are performed on an empty stack: pusheS); push(7); pop() ;

Ri

push(19); push(21);

I

pop() ;

Ha

ss

Top of Stack

an

Insert numbers in the following diagram to show what will be stored in the static stack after the operations above have executed.

Bottom of Stack

24. Suppose the fullowing operatiuns are performed on :m empty queue:

ad

enqueue ( 5 ) ; enqueue (7) ; enqueue (9) i enqueue(12);

uh a

m

m

Insert numbers in the following diagram to show what will be swred in the static stack after the operations above have executed.

from

rear

M

25. Suppose the following operarions are performed on an empty queue: enqueue(5); enqueue (7) ; dequeue { ); enqueue (9) i enqueue ( 12);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 18 Stacks and Queues

1102

us uf

dequeue ( ); enqueUe(lO)i

front

Yo

Insert numbers in the fo llowing diagram to show what will be stored in the static stack after the operations above have executed.

rear

26. What prob lem is overcome by using a ci rcular array for a static queue?

az

27. Write cwo different code segments that may be used to wrap an index back around to the beginning of an array when it moves past the end of the array. Use an if/else statement in one segme nt and modular arithmetic in the other.

31. T 32. T

F F

A staric stack or queue is built around an array.

The size of a dynamic stack or queue must be known in advance. The push operation inserts an element at the end of a stack. The pop operation retrieves an element from the tOp of a Stack. The STL stack container's pop operation does not retrieve the top element of the stack, it just removes it.

an

F F F

ss

28. T 29. T 30. T

Ri

True or False

Ha

Programming Challenges 1. Static Stack Template

ad

In this chapter you studied IntStacJc, a class that implements a static stack of integers. Write a template that will create a static stack of ally data type. Demonstrate the class with a driver program. 2. Dynamic Stack Template

m

In this chapter you studied DynlntStacJc, a class that implements a dynamic stack of integers. Write a template that wi ll create a dynamic stack of any data type. Demonstrare the class with a driver program.

m

3. Static Queue Template

uh a

In this chapter you studied IntQueue. a class that implements a static queue of integers. Write a template that wi ll create a static queue of any data type. Demonstrate the class with a driver program.

M

4. Dynamic Queue Template In this chapter you studied Dyn lntQueue, a class that implements a dynamic queue of intcgcrs. Write a template that will create a dynamic queue of any data type. Demonstrate the class with a driver program.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Quest,onsland Exercises

i

1103

us uf

5. Error Testing

~

V

Yo

The Oyn l ntStack and DynlntQueue classes shown in this c hapt~r are abstract data types using a dynamic stack and dynamic queue, respecti vely. The,classes do not currently test for memory allocaton errors. Modify the classes so they1determine whether new nodes cannot be created by handling the bad_aHoc exception. NOTE: If yo u have already done Program ming Challenges 2 and 4, T od ify the

l

templates yOll created.

I

6. Dynamic String Stack

az

Design a class that stores strings on a dynamic stack. The strings should not be fixed , in length. Demonstrate the class with a driver program.

Ri

7. Dynamic MarhStack

The MathStack class shown in this chapter on ly has twO member functions : add and sub. Write the following additonal member funct ions:

ss

div

Ha

addAll multAll

Description Pops the top two values off the stac k, multipl ies them, and pushes their product onto the stack. I Pops the top two values off the stack, divides the second value by the first, and pushes the quotient onto the sta1k. Pops all values off the stack, adds them, and pbshes thei r sum OntO the stack.

an

Function mult

Pops all values off the stack, multiplies them, r nd pushes their product onto the stack.

ad

Demonstrate the class with a driver program. 8. Dynamic MarhStack Template

m

Currently the MathStack class is derived from the IntStack class)" Modify it so it is a template, derived from the template you created in Programming Chall enge 2. 9. File Reverser

I

uh a

m

Write a program that opens a text file and reads its conte ntS into alstack of characters. The progra m should then pop the chara(;ters from the stnck and save them in a second text file. The order of the characters saved in the second file should be the reverse of their order in the fi rst file.

I

M

10. File Filter Write a program that opens a text file and reads its contents int~ a queue of characrers. The program should then dequeue each character, convert It to uppercase, and store it in a second file.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Stacks and Queues

i

Chapter 18

1104

Problem

Write a program that opens two text files and reads their contems into two separate queues. The program should then determine whether the files are identica l by comparing the characters in the queues. When two nonidentical characters are encountered, the program shou ld display a message indicating that the files are not the same. If both queues contain the same set of characters, a message should be displayed indicating that the files are identical.

Yo

-

Solving the File Compare

us uf

1l. File Compare

12. Inventory Bin Stack

Design an inventory class that stores the fo ll owing members:

An integer that holds a part's serial number. A member tha t holds the date the part was manufactured. An integer that holds the pa rt's lot number.

az

serialNum: m.anufactDate: lotNum.:

Ri

The class should have appro pr iate member functio ns for storing data into, and retrieving data from, these members.

Next, design a stack class that can hold objects of the class described above. If you

an

wish, you may use the template yOll designed in Programming Cha llenge 1 or 2.

ss

Last, design a program that uses the stack class described above. The program should have a loop that asks the user if he or she wishes to add a part to inventory, or take a part from inventory. The loop should repeat until the user is finished.

Ha

If the user wishes to add a part to inventory, the program should ask for the serial number, date of manufacture, and lot number. The data shou ld be stored in an inventory object, and pushed onto the stack.

If the user wishes to take a part from inventory, the program shou ld pop the top-most part from the stack and display the contents of its member va riables.

ad

When the user fin ishes the program, it shou ld display the contents of the member values of all the objects that remain on the stack. 13. Inventory Bin Queue

m

Modify the program you wrote for Programming Challenge 12 so it uses a queue instead of a stack . Compare the order in which the parts are removed from the bin for each p rogram.

m

14. Balanced Parentheses

M

uh a

A string of characters has balanced pa rentheses if each right parenthesis occurring in rhe string is matched with a preceding left parenthesis, in the same way that each right brace in a C++ program is matched with a preceding left brace. Write a program that uses a stack to determine whether a string emered at the keyboard has bala nced parentheses.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises

1105

i

I

us uf

15. Balanced Multi ple Delimiters

Yo

A string may use more than one type of delimiter to bracket informa tion into "blocks." For example, A string may use braces {I, parentheses ()~ and brackets [ J as delimitets. A string is properly delimited if each right delimiter is matched with a precedi ng left delimiter of the same type in such a way that either the resulting blocks of information are disjoint, or one of them is completely nested within , the othell. Write a program that uses a single stack to check whether a string conta'ning braces, parentheses, and brackets is properly delimi ted .

az

Serendipity Booksellers Software Development ProjectPart 18: A Problem-Solving Exercise I

Ri

For th is chapter's assignment, you will implement a queue dara Stnl¢ture for processing items p urchased at the cash register.

M

uh a

m

m

ad

Ha

ss

an

Previously you modified the cashier function to ask how many titles the custom.er is purchasing, and dynamica lly allocate an array of SoldBook objects large bnough ro ho ld that many titles. Modify the function so it stores the SoldBook objects in a queue instead o f the dynamic array. As the function dequeues the objects, it shou ld pe~form the necessary calculations to com pute the customer's sale and display the si mulated f ales slip.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m

m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

u

o

Introduction to Recursion Solving Problems w ith Recursion

, 9.3

Focus on Problem Solving and Program Design: The Recursive

, 9.5

Recursively Defined Problems Focus on Problem Solving and Program Design: Recursive

Binary Search Function

19.7 The Towers of Hanoi 19.8 Focus on Problem Solving and Program Design: Th e QuickSort Algorithm 19.9 Exhaustive Algorithms 19. 10 Focus on Software Engineering:

ss

Recursion VS. Iteration

Ha

Linked List Operations

Focus on Problem Solving and Program Oesign: A Recursive

an

19.4

gcd Function Focus on Problem Solving and Program Design: Solving

19.6

Ri

19.1 , 9.2

az

o

ad

Introduction to Recursion

m

CONCEPT: A recursive fun ction is one that calls itself.

m

You have seen instances of funct io ns calling other functions. Function A can call function B, which can then cal! funct ion C. It's also possible for a function to call itself. A function t hat calls itself is a recursive fu nction. Look at this message function:

uh a

void message ( ) {

cout ÂŤ "This is a recursive function. \n"; message ( );

M

)

Th is funct ion displays the string "This is a recursive funct ion.\n", and then ca1ls itself. Each time it calls itself, the cycle is repeated. Can you see a problem with the function?

1107

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1108

Recursion

i

Chapter 19

us uf

There's no way to stop the recu rsive calls. This fun ction is like an infin ite loop because there is no code ro stop it from repea ting.

Yo

NOTE: The fu nction example message will eventually ca use the program to cra sh. Do you remember lea rni ng In Cha pcer 18 thar rhe sysrem stores temporary data on a sta ck each time a function is ca lled? Eventually, these recursive function ca lls will use up all ava ilable stack memory, and cause it to overflow.

az

Like a loo p, a recursive function must have some method to control che number of cimes it repeats. The following is a modification of the message fUllction. It passes an integer argument, tha t holds the number of times the funct ion IS to ca ll Itse lf. void message(int times) {

Ri

i f (times> 0) {

cout ÂŤ "This is a recu rs ive function . \n "; message(times - 1); )

an

)

ss

T his function contains an i f statement tha t controls rhe repetit ion . As long as the times argument is grea ter than zero, it will display the message and call itself again. Each time it ca lls itse lf, it passes times - 1 as [he argument. For example, ler's say a program calls rhe fun ction with the followi ng sta temen t:

Ha

me ssage (5) ;

The argument, 5 , wil l ca use the function to cal! itself five times. T he first time the function is ca lled, th e i f statement will d isplay the message and chen ca ll irself with 4 as the argument. Figu re 19-1 illustrates this:

1st call of the function

Va l ue of times: 5

L

2nd call of Ihe fun cl;on

va l ue of times : 4

M

uh a

m

m

ad

Figure 19-1

The diagram in figure 19-1 illu strates twO separate calls of the message function. Each time the function is ca lled, a new instance of the times paramete r is created in memory. The firs t time the func tion is called, [he times parameter is set to 5. When the function calls itself, a new instance of time s is creared, and the value 4 is passed into it. This cycle repeats until, finally, zero is passed to the function. T his is illustrated in Figure 19-2.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1109

i

19.1 Introduction to Recursion

us uf

Figure 19-2 1st call of the function

Yo

Value of times; 5

2nd call of the function

â&#x20AC;˘

3rd call of the function

Ri

Value of times: 3

az

value of times ;

4th call 01 the function

an

value of times: 2

5th call of the function

Ha

ss

Value of times : 1 6th call of the function Value of times : 0

m

ad

As you can see from Figure 19-2 the fU ll ction is called a total of six times. T he first time it is called from main. and the o ther five rimes it calls itself. so the depth of recursion is five. When the fu nction reaches its sixth cail, the times parameter will be set co O. At that poim, the i f statement's conditional expression will be false, so the function will return. Control of the program will return from the sixth instance of the function to the point in the fifth msrance di rectl y after the recursive fun ction call: void message (int times)

M

uh a

m

{

if (times> 0 {

cout ÂŤ "This is a recursive function.\n" message (t imes - 1); - - - Recursive call }

.

Control returns here from the recursive call, causing the function to return.

Because there are no more statements to be executed after the fun ction ca ll , the fifth instance of the function returns control of the program back to the fourth instance. This repeats until all instances of the function return. Program 19-1 demonstrates the recursive mess age function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Recursion

i

Chapter 19

1110

1 2

3

us uf

Program 19-1 /1 This program demonstrates a simple recursive function . 'include <iostream> using namespace std ;

4

/1 Function prototype void message(intlj

6 7 8

lnt main()

9

(

16 17 18

)

az

15

message(5) i return 0;

// *** ** ** * * * ** ********** ••••••••••••••• • • • •••••••••••• * •• **** II Definition of function Message . If the value in times is *

Ri

10 11 12 13 14

Yo

5

/1 greater than 0, the message is displayed and the II function is recursively called with the argument 1/ times - 1.

void message (int times)

22 23

{ if (times> 0) (

24

25

cout«

26

message(times }

}

Output a a a a

recursive function . recursive function .

recursive function .

recursive function . a r e cursive function .

m

Program This i, This i, This i, This i, This i,

1);

ad

2B

"This is a recursive funct i on . \n " :

Ha

27

ss

21

an

19 20

• •

uh a

m

To further illustrate the inner workings of this recursive function, let's look at another version of the program . In Program 19-2, a message is displayed each time the func rion is emered, and another message is displayed JUSt before the funct ion rerurns.

1 2

3

II This program demonstrates a simple recursive function . finclude <iostream> using namespace std;

4

M

5 6

1/ Function protot ype

void message(int)i

7

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

19.1 Introduction to Recursion

8

i

10 11

int main() { message(5) i return 0;

12

}

13

11*********************************-****************** ********

II Definition of function message. If the value in times is * II greater than 0, the message is displayed and the function II is recursively called with the argument times - 1 . *

18

11*·*·* *·***·········********************************* ******** void message(int times) { COllt« "message called with" «times «

24

if (times> 0)

25

{

28 2.

}

30 31

cout « cout «

an

cout « "This is a recursive function. \n"; message(times - 1);

26 27

"message returning with " « " in times . \n";

times;

ss

32 Program Output

Ha

called with 5 in times . a recursive function . called with in times. a recursive function . called with 3 in times. a r ecursive function . called with 2 in times. a recursive function . called with 1 in times . a recursive fu nction . called with 0 in times . returning with 0 i n times. returning with 1 in times . returning with 2 in times . returning with 3 in times. returning with in times . returning with 5 in times.

m

m

ad

,

,

M

uh a

message This is message This is message This is message This is message This is me ss a ge message message message message message messe.ge

" in times.\n";

Ri

2J

az

"

20 21 22

Yo

14 15 16 17

us uf

.

1111

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 19

Recursion

us uf

i

1112

Solving Problems with Recursion

Yo

CONCEPT: A problem can be solved with recursion if it can be broken down in to successive smaller problems tha t are identica l to th e overall problem .

az

Programs 19- 1 and 19-2 in rhe previous section show simple demonstrations of how a recursive function works. But t hese examp les don't show us why we would wam to write a recursive function. Recursion can be a powerful tOol for solvi ng repetitive problems and is an important topic in upper-level computer science courses. What m ight nOt be clear to YOu yet is how to use recurs ion to solve a problem.

an

Ri

First, it should be noted that recursion is never absolutely required to solve a problem. Any problem that can be solved recursively can also be solved ite ratively, with a loop. In fact, recursive algorithms are usually less efficient than iterative algorithms. This is because a function cal l requ ires several actions to be performed by the C++ runtime sysrem. T hcse actions include allocating mcmory for parameters a nd loca l variable!>, and storing the address of the program location where control returns after the function terminates. These actions, which are sometimes referred co as overhead, take place w ith each function call. Such overhead is not necessary with a loop.

ss

Some repetitive problems, however, a re more easily solved with recursion than with iteration. Where an iterative algorithm mighr result in faster execution rime, rhe programmer

might be ab le CO design a recursive algo rithm faster.

Ha

In genera l, a recu rsive function works like th is:

If the problem can be solved now, without recursion, then the function solves it and returns. ff the problem cannot be solved now, then the function reduces it to a sma ller bur similar problem and calls itself to solve the smaller problem.

m

Problem wirh Recursion

In order to app ly this approach, we first identify at least one case in which the problem can be solved wi thout recurs ion. T his is known as the base case. Second, we determine a way to solve the problem in all other circumsta nces using recursion. This is called the recursive case. In the recursive case, we must always reduce the problem to a smaller version of the original problem. By reducing the problem with each recursive call, the base case will eventually be reached and the recursion will stop.

m

• Red ucing a

ad

uh a

Example: Using Recursion to Calculate the Factorial of a Number

M

Let's take an example from mathematics to exam in e an appl ica tion of recursion. In mathematics, the notat ion n! represents the factorial of the number n. The factor ial of a non negative number can be defined by the following rules:

If n '" 0 then Ifn>Othen

nl = 1

111

=1 x 2 X 3 X ... X n

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

19.2 Solving Problems with Recursion

us uf

i

111 3

Let's replace the notation n! whh facroria l(n), wh ich looks a bit more like compurer code, and rewrite these rules as lf n:O then If fI > 0 then

factorial{n) facrorial{n)

=1 =1 x 2 x 3 x .. . x n

Yo

These rules state tha t w hen n is 0, its factoria l is 1. When n is greater than 0, its factoria l is the product of all the posi tive in tegers from 1 up to fl. For instance, fac roria1{6) is calculated as 1 x 2 x 3 x 4 x 5 x 6.

az

When designing a recursive algorithm to calculate the factor ial of any number, we first idenrify the base case, w hich is rhe part of the calculation thar we can solve w ithout recursion. Tha t is the case where n is equal to 0:

Ri

If 11 = 0 [hen

This tells how to solve the problem when II is equal to 0, but what do we do when n is grea ter than O? T hat is the recursive case, o r the part of the problem that we usc recursion to solve . Th is is how we exp ress it: factorial{n) = n

x factorial{n - 1)

an

If n > 0 then

factorial{n)

factorialln)

=1

=n X facrorialln -I)

Ha

If n=O tnen

lf n>Othen

ss

T his states that if n is greater than 0. the fac torial of /I is n times the faccor ial of 11 - 1. Notice how the recursive call works on a reduced vers ion of the problem, n - 1. So, our recursive rule for calculating the facror ial of a n umber might look like chis:

T he following pseudocode shows how we m ight implement the factorial algorithm as a recursive function:

m

ad

factorial(n) If n is 0 then retur n 1 . else return n times the factorial of n - 1 . end f actorial .

m

H ere is the c ++ code for such a function : int f actorial(int nl

uh a

{

if (n .... 0) return 1 ;

e l se return n

II Base case

* factorial(n - 1) ; II Recursive case

M

)

P rogra m 19-3 demonstrates the recursive factOria l function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1114

Recurs}cm

us uf

i

Chapter 19

Program 19-3

5 6 7 8 9 10 11 12

Yo

4

// Function prototYpe int factorial{int);

int main{) {

iot number;

az

3

/1 This program demonstrates a recursive function to // calculate the factorial of a number . 'include <iostream> using namespace std;

1/ Get a number from the user. cout « "Enter an integer value and I will display\n"; cout « "its factoria l: " ; cin » number ;

13 14 15

16 17

20 21

22

}

ss

23

24

is ";

an

// Display the factorial of the number. cout « "The factorial of ,. « number « cout « factorial (number) « endl; return 0;

18 19

Ri

1 2

28 29

int factorial(int n)

30

{

if (n c_ 0) return 1; else return n * f actorial{n - 1);

31 32 33 34

}

/1 Base case // Recursive case

m

35

ad

25 26

Ha

27

//************************************************************* 1/ Definition of factorial. A recursive function to calculate * // the factorial of the parameter n. //************************************************ *** **********

uh a

m

Program Output with Example Input Shown In Bold Enter an integer value and I will display its factorial: 4 [Enter] The factorial of 4 is 24

In the example run of the program, thc factorial function is called with the argument 4 passed into n. Because n is not equal to 0, the if statement's else clause executes the following statement, in line 34:

M

return n

~

factorial(n -

1);

Although this is a return statement, it does not immediately return. Before the return value can be determined, the value of factor ial (num - 1) musr be determined. The factorial function is called recursively until the fifth call, in which the n parameter w ill be set to zero. The diagram in Figure 19-3 illustrates the value of n a nd the return value during each call of the function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

19.2 Solving Problems with Recursion

us uf

i

IllS

Figure 19-3 The function is first called from the main function. ---.~

First call of the fun ction

Yo

Value of n: 4 Return value: 24

The second th rough fifth cails are recursive. Second call of the function Value of n: 3

Ri

Return value: 6

az

'------.,.

Third call of the function

an

Value of n: 2

L-

Fourth call of the function Value 01 n: 1

Return value: 1

Fifth call of the function

Value of n: 0 Return value: 1

m

m

ad

Ha

ss

Return value: 2

uh a

T h is diagra m ill ustrates why a recursive algorithm must reduce the problem with each recursive ca ll. Eventually the recurs ion has ro Stop in order fo r a sol ution to be reached. If

each recursive call works on a smaller version of the problem, then [he recursive ca lls work tOwa rd the base case. The base case does not require recursion, so it stops the chain

M

of recursive calls.

Usually, :l problem is reduced by making the value of one or mOre parameters smaller with each recu rsive call. In OUf f a ctorial func ti on, the value of the parameter n gets closer to o with each recursive ca ll. When the parameter reaches 0, [he function returns a va lue w ithout making another rec ursive ca ll.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Example: Using Recursion to Count Characters

i

Recursion

us uf

Chapler 19

1116

Let'S look at another simple example of recursion. T he following function counts the number of times a specific character appears in a string. The line numbers are from Program 19-4, which we will examine momentarily. int numChars(char search, char str[], int subscript) {

i f (str{subscript] {

==

Yo

2B 29 30 31

'\0')

/1 Base case: The end of the string is reached. return 0;

32 33 34 35

else if (str[subscript] == search)

36

{

az

)

1/ Recursive case: A matching character was found .

38 39

II Return 1 plus the number of times the search II character appears in the rest of the string _

Ri

37

return 1 + numChars(search, str, subscript+l); ) else

43

{

/1 Recursive case: A character that does not match the II search character was found. Return the number of times II the search character appears in the rest o f the string. return numChars(search , str , subscript+l)i

47 48

ss

44 45 46

an

40 41 42

}

)

Ha

49

The functio n's parameters are

search: The character to be searc hed for and counted str: An array containing the string to be searched subscript: The starting subscript for the search

• • •

ad

When (his function exami n es a c ha racter in rhe s tring, three possibilities exis t,

m

The end of the string has been reached. This is the base case because there arc no more characters [Q sea rch. A character that matches the search character is fo und. This is a recursive case because we still have to search the rest of the string. A character that does nOt match the search character is found. This is also a recursive case because we still have to sea rch the rest of the suing.

m

uh a

Let's take a closer look a l the code. The fi rst if statemem, in line 30, determines whether the end of the stri ng has been reached:

M

if (str[subscript]

==

'\0')

Reaching the end of the string is the base case of the problem. If the end of the string has been reached, the function returns 0, indicating that 0 matchi ng characters were found at strlsubscript}. Otherwise, the following else i f clause, in lines 35 through 41, is executed:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1117

==

search)

t

Yo

/1 Recursive case : A matching character was found. II Return 1 plus the number of times the search II character appears in the rest of the string . return 1 + numChars(search, str , subscript+l );

us uf

else if (str(subscriptJ

i

19.2 Solving Problems with Recursion

az

If str [subscript] contains the search character, then we have found one matching char· acrer. Bur because we have not reached the end of the string, we must continue to search the rest of the string fo r more match ing cha ra cters. So, at th is point the function performs a recursive call. The return statement returns 1 pl us the number of times the search cha racrer appears in the string, starting at subscript + 1. In essence, this statement returns 1 plus the number of times the search cha racter appea rs in the rest of the st ring .

Ri

Finally, jf str[subscript] does not contain t he search character, the fol lowi ng else cla use in lines 42 through 48 is executed: else {

an

II Recursive case : A character that does not match the II search character was found. Return the number of t i mes II the search character appears in the rest o f the string. return numChars(search , str, subscript+l);

Ha

ss

The return statement in line 47 makes a recursive call to search the remainder of the string. In essence, this code returns the number of times the sea rch character appears in the rest o f rhe string. Program 19·4 demonstrares rhe funcrion.

Program 19·4

II This program demonstrates a recursive funct ion for coun t ing II the number of times a character appears in a string_ .include <iostream> using namespace std ;

ad

1 2 3 4 5

6 II Funct i on prototype 9

10

int main() {

11

char array l] ., "abcddddef";

12

1/ Display the number II 'd' appears in the cout « "The letter d « numChars ( 'd',

M

uh a

13 l4 15 16 17 18 19

m

int numChars(char, char f], int);

m

7 8

of times the letter string _ appears" array, 0) « " times . \n" ;

retu rn 0;

)

20

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 19-4

Recursion

i

Chapter 19

//* ********************** ••• *********************II Function numChars. This recursive f unction * II counts the number of times the character * /1 search appears in the string str. Th e search * II begins at th e subscript stored i n subscript. *

21

22 23 24

25

II* *·~ * ** *·* *********·**·****** ******* *****·******

28

int numC hars (char search, char str[J , int subscript)

29

{

30

if (str(subscript] == '\0')

Jl 32

{

az

26 27

us uf

(continued)

Yo

1118

1/ Base case; The end of the string is reached .

34

)

35 36

e lse if ( s tr [subscript] = = search) {

Ri

return 0 ;

33

an

/1 Recursive case: A matching character was found. II Retu rn 1 p lus th e number of times the search II character appears in t he r est of the string . return 1 + numChars( sear ch , str , subscript+l);

37 38 39 40 41 42 43

)

else {

II Recursive case : A character that does not match the II search charac t er was f ound . Retur n the number of times

ss

44 45

47

48 49

Ha

II the search character appears in the rest of t he string. return numChars(search, str, subscript+l) ;

46 )

)

ad

Program Output The letter d appears 4 times.

m

Direct and Indirect Recursion

m

The exa mp les we have discussed so fa r show recursive functions that direcrly call themselves. Th is is known as direct recursion . There is also the possibil ity of crea ting indirect recursion in a program. Thi s occurs when function A ca lls function B, which in turn calls function A. Th ere can even be severa! func tions invo!ved in the recursion. For example,

uh a

func tion A could call funcrio n B, which could ca ll function C, which calls fun ction A.

M

~

Checkpoint 19.1

What happens if a recursive funct ion never returns?

19.2

What is a recursive function 's base case?

19.3

What will the following program display? Jincl ude <iostream> using n cmespace std ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1119

i

19.3 Focus on Problem Solving and Program Design: The Recursive gcd Function

us uf

II Funct ion prototype v oid showMejint arg);

int mainj) (

lnt num

= 0;

Yo

ShOwMe(num) ; return 0; )

void showMe(int arg) (

i f (arg < 10)

az

showMe j ++arg) ; else cout « arg « endl;

19.4

Ri

)

What is the difference between direct and in di rect recursion?

an

Focus on Problem Solving and Program Design: The Recursive ged Function

Ha

ss

CONCEPT: The gcd function uses recursion £0 find the greatest common divisor (CeD) of two numbers.

Our next example of recursion is the ca lcul ation of the greatest common divisor, or ceo, of two numbers . Using Eucl id's algorithm, the GCD of two positive integers, x and y, is: jf y divides x evenly otherw ise

ad

gcd(x, y ) : y; gcd(y, rema inder of x/Y)j

m

The definition above states that the GCD of x and y is y jf xly has no remainder. Otherwise, the answer is the GCD of y and the remainder of x/yo Program 19-5 shows the recu rsive C++ imp lementation:

1

2 3 4

II This program demonstrates a recursive function to calculate 1/ the greatest common diviso r (gcd) of two numbers. 'include <iostream> us i ng namespace std;

uh a

,

m

Program 19-5

6

7

II Function prototype i nt gcd(int, int);

M

8

(program conrinues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Recursion

Program 19-5 iot main()

( iot num!, nurn2;

11

12 13

cout «

cin »

I.

"Enter two integers : "; numl » num2;

II Dis p lay the GCD of the numbers . "The greatest corronon divisor of " « cout « " and" « num2 « " is " ; cout « gcd(numl, num2) « endl;

17

cout «

18 19 20

retur n 0;

Ri

)

numl;

Yo

II Get two numbers.

14 15

21 22 23

(continued)

az

9

10

i

Chapter 19

us uf

1120

2425 11*·········· __·_----_·_-------------------------_··-- ****** II Definition of ged. This function uses recursion to II calculate the grea t est common divisor of two i ntegers, * /1 passed into the parameters x and y. *

28

//******************************************** ••• **********

29 30

int ged( lot x, lnt y)

Jl

(

i f (x

J2 JJ

Y

0)

II Base case

y) ;

II Recursive case

Ha

J4

35 36

return y; else return gcd(y, x %

ss

26

an

27

)

Program Output with Example Input Shown In Bold Enter two integers : 4928 [Enter]

ad

The greatest common divisor of 49 and 2 8 is 7

m

m

Focus on Problem Solving and Program Design: Solving Recursively Defined Problems CONCEPT: Some mathematica l problems are designed for a recursive sol ution.

uh a

Some mathematical problems are designed to be solved rec ursively. One well -known example is the calculation of Fibonacci numbers. The Fi bonacci numbers, named after the Italian mathematician Leonardo Fibonacci (born circa 1170), are the followi ng sequence:

M

0,1, 1,2,3,5,8,13,21,34,55,89,144,233, ... Notice (har after [he second number, each number in the series is the sum of the ous numbers. The Fibonacci series can be defined as

twO

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

previ-


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

11 2 1

i

19.4 Focus on Problem Solving and Program Design: Solving Recursively Defined Problems

FN = FN_ 1 ... FN_2

us uf

Fo =0 FJ =1

for N? 2.

A recursive C++ function to calculate the nth number in the Fibonacci series is shown here:

Yo

int f ib (int n) {

return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 2); )

az

i f (n < ... 0)

Ri

The functi on is demonstrated in Program 19-6, which displays the first 10 numbers in the Fibonacci series.

Program 19-6

3 4

an

1 II This program demonstrates a recursive function 2 II that calculates Fibonacci numbers.

*include <iostream> us ing namespace std;

int fib(int);

9

int main()

{

13

ad

cout « "The first 10 Fibo nacc i numbers are : \n" ; for (int x = 0: x < 10; x++) cout « fib(x) « .... i cout « endl: return 0 ;

11 12 14 15 16

)

17

m

20

int fib(int n) { if (n <= 0) return 0; II Base case else if (n == 1) return 1; II Base case else re tur n fib(n - 1) + fib(n - 2); II Recursive case

uh a

21 22 23 24

11 ************* **************************** II function fib. Accepts an int argument * 1/ in n. This function returns the nth * II Fibonacci number. • 1/* **** ****** ****************** ******* *****

m

18 19

Ha

II Function prototype

6 7 8

10

ss

5

25 26 27

28

29

M

30 31 32

)

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Recursion

Program 19·6

i

Chapter 19

(continued)

us uf

1122

Program Output The first 10 Fi bonacci numbers are : 1 1 2 3 5

a

13 21 34

Yo

o

Another such example is Ackermann's func tion . A Programming C hallenge at the end of th is chapter asks you to write a recursive function that calculates Acke rma nn's function.

Focus on Problem Solving and Program Design:

az

Recursive Linked List Operations

Ri

CONCEPT: Recursion ca n be used to traverse the nodes in a lin ked Jist. Recall that in Chapter 17 we discussed a class named

NumberList

that holds a li nked list

of double values. In this section we will modify the class by add ing recursive member

an

functions. The functions wi ll use recursion to traverse the linked list and perform the following opera tions:

Count the number of nodes in the list.

Ha

ss

To count the number of nodes in t he list by recursion , we introduce rwo new member function s: numNodes and countNodes. countNodes is a private member function that uses recursion, and numNodes is the p ublic interface that calls it. Display the value of the list nodes in reverse order.

d isplay the nodes in the list in reverse order, we introduce twO new member functions: displayBackwards and showReverse. showReverse is a private member fu ncrion that uses recursion, and displayBackwards is the public interface that calls it.

ad

To

The class declaration, which is saved in NumberList. h, is shown here: 2 3

II Specification file for the NumberList class lifndef NUMBERLIST H 'define NUMBERLIST H

4 5

class NumberList

m

1

{

7 8 9

private : 1/ Declare a structure for the list struct ListNode

uh a

m

6

10

{ double value;

11

struct ListNode *next;

M

12

13 14

};

15

ListNode *head ;

// List head pointer

16

17 18 19

II Private member functions int countNodes(ListNode *) canst; void shawReverse{ListNode *) const;

20

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

19.5 Focus on Problem Solving and Program Design: Recursive Linked List Operations

24

25 26

i us uf

public : II Constructor NllmberList ( ) { head == NULL ; )

21 22 23

Yo

II Dest r uctor -NumberList() ;

27

32

33 34 35 36

37

3.

);

39

tendif

)

Ri

II Linked List Operations void appendNode(double)i void insertNode(double)i void deleteNode(double )i void displayList() const; int nurnNodes ( ) canst { return countNodes(head); void displayBackwards() const { showReverse(head) ; )

29

az

2. 30 31

1123

an

Counting the Nodes in the List

ss

The numNodes function is declared inline. It simply calls the cOllntNodes funct ion and pa sses [he head pointer as an argument. (Because t he head poinrer, which is p rivate, m ust be passed to countNodes, the numNodes function is needed as an interface.)

The function definition for countNodes is shown here: int NumberL i st : : countNodes( ListNode *nodePt r) const

174

(

Ha

173

i f (nodePtr !: NULL ) return 1 + countNode s(nod ePtr - >nex tj; else return 0;

175 176 177 178 179

ad

}

T he function's recursive logic can be expressed as:

m

If the current node has a value Return 1 + the number of the remaining nodes . Else

m

Return O.

End I f .

uh a

Program 19路7 demonstrates the function.

Program 19-7 1

II This program counts the nodes i n a list .

#include <iostream>

)

'include "NumberList.h"

4 5

u s ing namespaca std;

M

2

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 19-7

(continued)

lnt main ( ) { canst int MAX

= 10;

us uf

6 7 8

Recursion

i

Chapter 19

1124

II Maximum number of values

9

II Define a NumberList object . NumberList list;

Yo

10 11 12 13 14 15

II Build t he list with a se r ies of numbers. for (int x = 0; x < MAX; x++) list . insertNode(x) ;

Ri

II Dis p lay the number of nodes in the list . cout « "The number of nodes is " « list .numNodes() « end1 ; return 0 ;

az

16

17 18 19 20 21

)

an

Program Output The number o f nodes is 10

Displaying List Nodes in Reverse Order

void NumberList :: showReVerSe(ListNode *nodePtr) const { if (nodePtr != NULL) { showReverse(nodePtr->next); cout « nodeptr - >va lue « " ";

ad

187 188 189 190 191 192

Ha

ss

The techniq ue for displa ying the list nodes in reverse order is designed like the node counting procedure: A publ ic member function, which serves as an interface, passes the head pointer to a private member function. The public d i splayBackwards function, decla red inline, is t he interface. It ca lls the showReverse func tion and passes the head pointer as an argument. T he fu nction definition for showReverse is shown here:

}

m

193

194

}

M

uh a

m

T he base case for the funct ion is nodePtr being eq ual to NULL When this is true, the fun ction has reached rhe last node in the list, so it tetutl1s. It is not umil this happens tha t any instances of t he cout sta tement execu te. T he instance of the func tion whose nodeptr variable poin ts ro the last node in the list will be the first ro execute the cout statement. It wi ll t hen ret urn, and the prev ious instance of the function will execute its cout statement. T his repeats until a ll the instances of the func tion have returned. The modified class declaratio n is stored in NurnberList . h, and its member function implementatio n is in NumberList . cpp. The remainder of the class implementation is unchanged from Chapter 17, so it is not shown here. Program 19-8 demonstrates the function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1125

us uf

i

19.6 Focus on Problem Solving and Program Design : A Recursive Binary Search Function

1 2 ) 4 5

II This program demonstrates the recursive function II for displaying the list's nodes in reverse . 'include <iostream> lIinclude "'NumberList.h"' using namespace std:

6

intmain() { const double MAX

= 10.0;

/1 Upper limit of values

/1 Create a NumberList object. NumberList list;

az

7 8 9 10 11 12

II Add a series of numbers to the list. for (double x = 1 . 5; x < MAX; x += 1.1) l ist.appendNOde(x);

17

II Display the values in the list . cout « "' Here are the values in the list:\n": list . disp l ayList();

an

18 19 20 21 22

ss

1/ Display the values in reverse order. cout « "Here are the values in reverse order : \n": list . displayBackwards(); return 0 :

23 24 25 }

Ha

26

Ri

13

14 15 16

Yo

Program 19·8

Program Output Here are the values in the list : 1.5 2.6

ad

3.7

4.8 5.9

9.2

m

7

8. 1

m

Here are the values in reverse order : 9.2 8.1 7 5.9 4.8 3 . 7 2 . 6 1.5

uh a

Focus on Problem Solving and Program Design: A Recursive Binary Search Function

M

CONCEPT: T he bin ary search algori thm can be defined as a recursive function.

In Chapter 8 you learned about the binary search algorithm and saw an iterative example written in C++. The binary search algorithm can also be implemented recursively. For example, the procedure can be expressed as If array[middle] equals the search value, then the value is found .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 19

Recursion

us uf

i

11 2 6

Else, if array[middle] is less than the search value, perform a bi nary search on the upper half of the array. Else, if array[middle] is greater than the search value, perform a binary search on the lower half of the array .

Yo

T he recursive binary sea rch algorithm is an example of breaking a problem down lOrc smaller pieces until it is solved. A recurs ive binary search function is shown here: int binarySearch(int arrayl], i nt first, iot last, iot value) {

int midd l e ;

II Midpoi nt of search

an

Ri

az

if (first> last) return -1 ; midd le ~ (first + la st) I 2; i f (array(middle] == value) return middlei if (array[middle) < va lue) return binarySearch(array, middle+l, las t , value)i else return binarySearch(array, first , middle-l,value) i )

Ha

ss

T he first parameter, array, is the array to be searched . The next parameter, first, holds the subscript of the firSt element in the search range (the portion of the array to be searched). The next para meter, last, holds the subscript of the last element in the search range. The last parameter, value, holds the va lue to be searched for. Like the iterative version, this function returns the subsc ript of the value if it is found, or -1 if the value is not found. Program 19-9 demonstnltes the function. Program 19-9

ad

5 6

'include <iostream> using names pace std ;

II Function prototype

lot binarySearch(int (J, int, int, int);

m

,

II This program demonstrates the recursive binary Search function.

7

8

const int SIZE = 20i

9

II Array size

m

1 2 3

10

int main()

11 12

{

II Define an array of employee 10 numbe rs l nt tests[SIZEj ~ {101 , 142, 147 , 189, 199 , 207, 222, 234 , 289, 296 , 310 , 319 , 388 , 394, 417 , 429 , 447 , 521 , 536 , 600} i int empID; // To hold an 10 number iot results ; 1/ To hold the search results

uh a 13

I'

15 16

M

17 18

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

11 27

19

II Get an employee 10 number to search for. cout « "Enter the Employee ID you wish to search for: "; cin » emplO;

20 21

22

II Search for the ID number in the array. results: binarysearch(tests, 0, SIZE - 1, empID):

25

26

If

Display the results of the search , if (results == -1) cout « "That number does not exist in the array . \ n": else

27 28 29 30 31

{

43 44 45

46 47 48

49 50 51

II II II II

1/ /I /I //

az

Ri

The binarySearch function performs a recursive binary search on a range of elements of an integer array passed into the • parameter array. The parameter first holds the subsc ript of • the range's starting element, and last holds the subscript • of the range's last element. The parameter value holds the • search value . If the search value is found , its array • subscript is returned , Otherwise, -1 is returned indicating • the value was not in the array. •

an

42

)

ss

40 41

)

return 0;

results ;

ff ···················································· ... * •••••••

Ha

38 39

"That 10 is f ound at element " « " in the array\n";

cout « cout «

32 33 34 35 36

Yo

23 24

int binarySearch(int array!], int first, i nt last , int value) {

int middle;

ff

Midpoint of s earch

if (first> last) return -1;

54 55 56 57 58 59

middle ~ (first + last)f2 ; if (array{middlej Eavalue) return middle: if (arr ay[middle]<va l ue) return binarySearch(array, middle+l,last,value)i else return bina rySearch(array, first,middle-l,value);

uh a

)

m

m

ad

52 53

60 61

us uf

i

19.6 Focus on Problem Solving and Program Design: A Recursive Binary Search Function

M

Program Output with Example Input Shown In Bold Enter the Employee 10 you wish to search for : 521 [Enter] That 10 is found at element 17 in the array

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Ch<'lpter 19

Recursion

us uf

i

1128

The Towers of Hanoi

Yo

CONCEPT: The repetitive steps involved in solving the Towers of Hanoi game can be easil y impl emented in a recu rsive a1gorithm.

az

The Towers of Hanoi is a mathematical game that is often used in compurer science textbooks to illustrate the power of recursion. Th e game uses three pegs and a set of discs with holes through their cente rs. The discs are sta cked on one of the pegs as shown in Figure 19-4.

an

Ri

Figure 19-4 The pegs and discs In the Towers of Hanoi game

Ha

ss

Notice that the discs are stacked on the leftmost peg, in order of size with the largest disc at the bottom. The game is based on a legend in which a group of monks in a temple in Hanoi have a similar set of pegs with 64 discs. The job of the monks is to move the discs from the first peg to the third peg. The middle peg can be used as a temporary holder. Furthermore, the monks mllst follow these cules wh ile moving the discs: •

Only one disc may be m oved at a time. A disc ca nnot be placed on top of a smaller disc. All discs must be stored on a peg except while bei ng moved.

ad

m

According to the legend, when the monks have moved all of the discs from the first peg to the last peg, the world will come to an end.

uh a

m

To play the game, you must move all of the discs fro m the fi rst peg to the third peg, fol lowing the same rules as the monks. Let's look at some example solutions to this game, fo r differenr numbers of discs . If you only have one disc, the soluti on to the game is simple: move the disc from peg 1 to peg 3 . If you ha ve twO discs, the solu tion requi res three moves:

M

• • •

Move disc 1 to peg 2. M ove disc 2 to peg 3. Move disc 1 to peg 3.

Notice that this approach uses peg 2 as a temporary loca tion. The complexity of the moves contin ues to increase as the number of discs increases. To move three discs req uires (he seven moves shown in Figure 19-5.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

, 9.7 The Towers of Hanoi

i

1 1 29

Yo

us uf

Figure 19-5

First move ; Move disc 1 to peg 3.

az

Original setup.

Second move: Move disc 2 to peg 2.

Ri

Third move: Move disc 1 to peg 2.

"

Fourth move: Move disc 3 to peg 3.

Ha

ss

â&#x20AC;˘

an

,,

,,

Sixth move: Move disc 2 to peg 3.

Fifth move : Move disc 1 to peg 1 .

,,

Seventh move: Move disc 1 to peg 3.

The following statemenr describes the overall solution to the problem: 11

discs (rom peg 1 to peg 3 usillg peg 2 as a temporary peg.

ad

Moue

m

The following algorithm can be used as the basis of a recursive function that simulates the solu tion to the game. Norice that in this algorithm we use the variables A. B. and C co hold peg numbers.

M

uh a

m

To moue 11 dis cs from peg A to peg C, llsing peg B as a temporary peg: Ifn> 0 Then MOlle 11 - 1 discs (rom peg A to peg B, using peg C as a temporary peg. Moue the remaining disc from the peg A to peg C. Move n - 1 discs from peg B to peg C, using peg A as a temporary peg. End If

The base case for rhe algorithm is reached when there are no more discs to move. The followi ng code is for a function that implements th is algorithm. Note that the function does not actually move anything, but displays instructions indicating all of the disc moves to make.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 19

Recursion

us uf

i

1130

void moveDiscs(int num, int fromPeg, i nt toPeg, int tempPeg) {

i f (num > 0) {

Yo

moveD iscs(num - 1 , fromPeg, t empPeg, toPeg ); cout « "Move a disc from peg " « fromPeg « " t o peg " « tOPeg « endl; moveDiscs(num - 1, tempPeg, toPeg, fr omPeg ) ; )

num

The number o f discs t o move.

fromPeg

The peg

toPeg

T he peg to move the discs to.

tempPeg

The peg to use as a temporary peg.

Ri

to move the discs fro m .

az

This funcrion accepts arguments into the following three parameters:

If num is greater tha n 0, then there are discs to move. The first recursive ca ll is moveDiscs(num - I, frornPeg, tempPeg, toPeg);

«

"Move a disc from peg " « fromPeg toPeg « end 1 ;

,. t o peg " «

ss

cout «

an

This sta tement is an instruct ion to move all but one disc from fromPeg to tempPeg. usi ng tOPeg as a tempora ry peg. The next state ment is

Ha

Th is si mply displays a message indicating that a disc should be moved from fromPeg to toPeg. Nex t, a nother recursive ca ll is executed : moveOiscs(num - 1, tempPeg, toPeg, framPeg) ;

Program 19-10

II This program displays a solution to the Towers of II Hanoi game. 'include <iostream> usin g names pace std;

m

1 2 3 4

II Function prototype vo id moveDi s cs(int, int, int , int ) i

uh a

8 9 10 11

m

5

6 7

12

13

M

I.

15

ad

This statement is an instru ction to move all but o nc disc from tempPeg to toPeg. using fromP eg as a temporary peg. Program 1 9-10 demonstrates this function.

int mai n{) {

co nst const canst const

int NUM DISCS

int FROM

PEG

= 3; = 1;

int TO PEG = 3 ; 2; int TEMP PEG

-

II II II II

Number of discs to move Initi al "fromH peg Init ial "to" peg Initia l "temp" peg

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1131

16

II Play the game.

17

moveOiscs(NUM DISCS , FROM_PEG, TO_PEG, TEMP_ PEG) ; cout « "Al l the pegs are moved! \ n " ;

18 20 21

I

23

II

2'27 28 29

• • • •

• •

az

25

disc move in The moveDiscs functio n displays /I the Towers of Ha noi game . /I The paramete r s are : num : The number of d iscs to move . /I frompeg: The peg t o move from . II tOPeg : The peg to move to. II tempPeg : The temporary peg . II

Yo

return 0;

19

2'

us uf

i

, 9.8 Focus on Problem Solving and Program Design : The QuickSort Algorithm

M

)

ss

40

41

an

void moveOiscs(int num , iot fromPeg , i n t toPeg, int tempPeg ) { if (nurn > 0) ( moveOiscs(num - 1, fromPe~, tempPeg, toPeg) ; cout « MMove a d isc fr om peg " « fromPeg « to peg" « toPeg « endl; moveDiscs(num - 1, tempPeg. toPeg . fromPeg); )

Program Output 1 1

3 1 2 2 1

to to to to to to to

peg peg peg peg peg peg peg

ad

peg pe g peg peg peg peg peg

3 2 2

3 1

3

3

moved!

m

Move a disc from Move a di sc from Move a disc from Move a disc from Move & d isc from Move a d isc fr om Move a disc from All the pegs are

Ha

34 35 36 31 38 39

Ri

30 11*·························*····*···················

31 32 33

uh am

Focus on Problem Solving and Program Design: The QuickSort Algorithm

M

CONCEPT: The QuickSort algorithm uses recursion to efficiently sort a list.

The QuickSort algorithm is a popular general-purpose sorring routine developed in 1960 by C.A.R. Hoare. I[ can bc used to sort lists stored in arrays or linear linked lists. It sorts a list by di viding if inro twO sublists. Between the sublists is a selected value known as [he pivot. This is illustrated in Figure 19-6.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 19 Recursion

us uf

i

1132

Figure 19-6

r~ r

i

Sublist 1

1

Sublist 2

Yo

Pivot

az

Notice in the figure that sublisr 1 is positio ned to the left of (before) the pivot, and subl isr 2 is positioned [0 the right of (after) the pivot. Once a pivot va lue has been selected, the algorithm exchanges the Other values in the list until all the elements in sublist 1 are less than the pivot, and all the elements in sublist 2 are greate r than the pivot.

Ri

Once this is done, the algorithm repeats the procedure on sublist 1, and then on subii st 2. The recursion StopS when there is only one element in a sublist. At that point the original list is comp letely sorted.

an

The algorithm is coded primarily in two functio ns: quickSort and partition. guickSort is a recursive fu nction . Its pseudocode is shown here:

ss

quickSort : If Starting Index < Ending Index Partition the List around a pivot. quickSort Sublist 1. quickSort Sublist 2.

Ha

End If .

Here is the C++ code for the qu ickSort funct ion: void quickSort( int set[), int start, int end) (

int pivotPoint;

II Get the pivot point. pivotPoint ~ partition(set, sta r t, end); II Sort the first sublist . quickSort(set, start , pivotPoint - 1): II Sort the second sublist. quickSort(set, pivot Po int + 1, end);

m

m

(

ad

if (start < end)

)

uh a

}

M

This version of quickSort works wi th an array of integers. Its first argument is the array holding the list rhar is to be sorted . The second and third arguments arc the starring and ending subscripts of the li st. The subscript of the pivot element is retllrned by the partition function. partition nor only determines which element will be the pivor, blle also cont[Qis rhe rearranging of the

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

19.8 focus on Problem Solving and Program Design: The QukkSort Algorithm

us uf

i

1133

other values in the list. Our version of rhis funcrion selects rhe eJemem ill (he middle of the list as the pivot, then sca ns [he remainder of the list searching for values less than the pivot. The code for the parti tion fu nction is shown here: int partition(int set[l, iot start, int end)

Yo

(

int pivotValue, pivotlndex, mid;

~ (start + end) I 2; 5wap(set[start], set(mid); pivot Inde x = start ; pivotValue = set[startli for (int scan = start + 1; scan <- end ; scan++)

az

mid

(

if (set[scan] < pivotValue)

Ri

(

pivotlndex++; swap(set[pivotlndex], set[scan]); ) )

an

swap(set(startj, set [ pivotlndex}): return pivotlndexj

NOTE: T he partition function does not initially sort the va lues into thei r final order.

Its job is only to move the values that are less than the pivot to the pi vot's left, and move the values that are grea ter than the pivot to the pivot 's right. As long as that condition is met, they may appear in any order. The ultimate sorting order of rhe entire li st is ach ieved cumulatively, though the recursive calls to quickSort.

Ha

<)

ss

)

ad

There are many different ways of partitioning the list. As previously stated, the method shown in the funct ion above selects the midd le value as the pivot. T har value is then moved to the beginning of the list (by exchanging it with the value stored there). This simplifies the next step, which is to scan the list.

m

A for loop scans the remainder of the list, and when an element is found whose value is less than rhe pi vot, that value is moved ro a location left of the pivor point.

m

A third function, swap. is used to swap the va lues found in any two elements of the list. Tht: function is shown below.

uh a

void swap{int &valuel , int &value2) (

int temp = valuel; valuel =' value2i value2 = temp;

M

)

Program 19- 1' demonstrates [he QuickSorr algorithm shown here.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 19

Recursion

us uf

i

1134

Program 19-11

5 6 7 8

II This program demonstrates the QuickSort Algorithm. 'include <iostream> using namespace std; II Function prototypes void quickSort( i nt (I, int, lnt); int partition(int [J, into int) ; void swap(int &, int &); int main ()

11

{

az

9 10

Yo

1 2 3 4

canst int SIZE = 10; II Array size int count; II Loop counter int array[SIZE) = {7. 3, 9, 2 , 0 , 1, 8 , 4, 6, 5};

16

II Disp l ay the array contents . for (count = 0; count < SIZE; count++) cout « array[countj « " "j cout « endl;

18 19

20

21

II Sort the array . quickSort(array, 0, SIZE - l) j

ss

22 23 24

26 27 28

Ha

II Display the array contents . for (count = 0; count < SIZE; count++) cout « array(count] « " "j cout « endl; return OJ

25

29

an

17

Ri

12 13 14 15

)

30

11************ ********* ******* ********* ******* ** **

32 J3

II quickSort uses the quicKsort algorithm to II sor t set , from set[start] through set[endj .

34

11************************************************

35 36

void quickSort(int set[], int start , int end)

37

{

m

int pivotPointj

if (start < end) { II Get the p i vot point . pivotPoint ~ partition(set. start, end) ; II Sort the first sublist . quickSort(set, start, pivot Point - l ) i

uh a

42 43

m

38 39 40 41

ad

31

,.

M

45

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

T9.8 Focus on Problem Solving and Program Design: The QuickSort Algorithm

46 47

us uf

i

1135

1/ Sort the second sublist. quickSort{set, pivotPoint + 1, end);

"50"

)

Yo

)

partition selects the va~ue in the middle o f the • array set as t he pivot . The list is rearranged so • all the values less than the pivot are on its left • and all the values greater than pivot are on its right . •

II /I II /I

56

Ilk******** **********.***********************.****.*** ******

57

"

62 63 64 65 66

mid - (start + end) I 2; swap(set[start], set(mid]); pivot Index = start; pivotValue set[startj i for (int scan = start + 1; scan <= endi scan++)

(

'9

if (set{scan] < pivotValue) (

an

=

'7'8

ss

pivotlndex++ ; swap(set(pivotlndex], set{sca nJ);

70 71 72 73

74 75 16

Ri

int partition(int set(], int start, int end) { int pivotValue , pivotlndex, mid;

) )

Ha

58 59 60

az

52 53 54 55

swap(set[start], set[pivotlndex]) : return pivotlndeXi )

77

II swap simp ly exchanges the contents of

80

II valuol and value2 .

81

11 ····*·***.****.***.*.* •• ****.* ••••• *•••• *.

ad

79

m

82 83

void swap/int &valuel, int &value2)

8'

(

85

int temp

valuel;

uh am

8'

• •

87 88 89

valuel = value2; value2 - temp;

)

Program Output

7 3 9 2 0 1 8 4 6 5 1 2 3 4 5 6 789

M

o

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 19

Recursion

us uf

i

1136

Exhaustive Algorithms

CONCEPT: An exhaustive algorithm is one that finds a best combination of items by

Yo

looking at an th e possible combinations.

az

Recursion is helpfu l if you need to exami ne many possible combinations and idenrify the best combination. For exa mple, co nsider all the d ifferent ways you can make cha nge for $1.00 Llsing our system of coins:

Ri

1 dollar piece, or 2 fi fty-cent pieces, or 4 quarters, or 1 fi fe y-cent piece and 2 quarters, or 3 Quarters, 2 dimes, and 1 nickel, or . .. there are many more possibilities.

an

Although rhere are many ways to make change for $1.00, some ways are bencr than others. For example, you would probab ly rather give a single dollar piece instead of 100 pennies.

Ha

ss

An algorithm that looks at a ll the possible combi nations of items in order to nnd the best combi nation of items is called an exhaustive algorithm. Program 19-12 presenrs a recursive function that exhaustively tries all the poss ible comb inations of coins. The program then displays the total number of combi nations that ca n be used to make the specified change, and the best combination of coins.

Program 19-12

m

m

ad

1 II This p ~ ogram demonstrates a recursive function that e xh austivel y 2 II searche s through all possible combinations o f coin va lues to find 3 II the best way to make change for a specified amount . 4 ' include <ios tream> 5 u s in g names pace std: 6 7 II Constants 8 const int MAX_COINS_CHANGE ~ lOa: II Max number of coins to give i n change II Max number o f coin values 10 const int NO_ SOLUTION INT_ MAX; II Indicates n o so l ution 11

12 II Fu nction prototype

uh a

13 void make Change(int, int, i nti I, i nt): 14

15 II coinValues - g l obal array of coin values to choose from 16 lnt coinvalueS\MAX_CO IN_VALUESj = {lOO, 50 , 25, 10, 5 , 1 }; 17

M

18

II

bestCoins - global array of best coins to make change with

19 int bestCo i ns(MAX_COINS_ CHANGEj ;

20

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1137

21 II Global variables 22 int numBestCoins ~ NO_SOLUTION, 23 numSolutions ~ 0 , 24 numCoins;

us uf

i

19.9 Exhaustive Algorithms

/1 Number of coins in bestCoins 1/ Number of ways to make change II Number of allowable coins

25

29 30 31

Yo

26 27 int main() 28 {

int coinsUsed(MAX_COINS CHANGE], II List of coins used II The number of coins used numCoinsUsed ~ 0 , 1/ The amount to make change f or amount ;

32

II Display the poss i ble coin va l ues . cout « "Here a r e the valid coin values, in cents : " ,. for (int index ~ 0; index < 5: i ndex++) cout « coinValues[i ndex] « " ";

37

cout « endl i

38 39

II Get input from the user.

40

cout«

"Ente:.- the a mou n t

of

cents

« "to make change for : " ,.

(as an integer) "

an

41

Ri

az

33 34 35 36

cin» amount ; cout« "What is the maximum number of coins to give as change? n; cin ~> numCoins;

45 46 47

/1 Call the recur si ve function . makeChange(numCoins, amount , coinsUsed , numCoinsUsed);

55 56

Ha

50 51 52 53 54

II Display the results . cout « "Number of possible COmbi nations: " « cout « "Best combinat i on of coins : \n"; if (numBestCoins ~~ NO_SOLUTION) cout « "\tNo solution\n"; else {

cout « endl; return 0;

m

m

)

59 60

63

endl;

for (int count ~ 0 ; count < nurnBestCoins; count++) cout « bestcoins[count] « " ";

57 58

61 ) 62

numSolutions «

ad

4.

49

ss

43 44

42

• • • • *

69 I I

*

uh a

64 II Func tion makeChange . This fUnction uses the following parameters : 65 II coinsLeft - The number of coins left to choose from. 66 II amount - The amount to ma ke change for. 67 II coinsUsed - An array that conta i ns the coin va lues used so far . 68 II numCoinsUsed - The number of values in the coinsUsed array .

M

70 /1 This recursive func t ion finds all the possible way s to make change • 71 II foe the value in amount. The best combination of coins is stored in ~ 72 I I the array bestCoins . *

73 11· *···**** ••••• * •••••• *··* ••••••• *.*** •••• ******* •• • • *.** *** •• ********. (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Recursion

Program 19路12

i

Chapter 19

(continued)

7. 75 void makechange(int coinsLeft, int amount, int coinsUsed[), 76 int numCoinsUsed) {

78 79

int coinPOS, count;

II To calculate array position of coin being used II Loop counter

Yo

77

80

98 99 100 101 102 103

az

Ri

{

for (count = 0: count < numCoinsUsed; count++) bestCoins(count] = coinsUsed(count]i numBestCoins = numCoinsUsed;

)

II Find the other combinations using the coin coinPos = numCoins - coinsLefti coinsUsed[numCoinsUsedJ = coinValues ! coinpos }; numCoinsUsed++; makeChange ( coinsLeft , amount - cOi nValues{coi nPos }, coinsUsed, numCoinsUsed);

10'

II Find the other combinations not using the coin. numCoinsUsed --; makeChange(coinsLeft - l, amount, coinsUsed, numcoinsUsed);

ad

lOS 106 107 108 }

an

) numSolutions++: return :

ss

B7 88 89 90 91 92 93 94 9S 96 97

if (COinsLeft == 0) II If no more coins are left return; else i f (amount < 0) II If amount to make change for is negative return; else if (amount == 0) II If solution is found { II Store as bestCoins if best if (numCoinsUsed < numBestCoins)

Ha

81 92 83 84 B5 86

us uf

1138

m

Program Output with Example Input Shown In Bold

uh a

50 10 1 1

m

Here are the valid coin values, in cents : 10 0 50 25 10 5 1 Enter t he amount of cents (as an integer) to make change for: 62 [Enter] What is the maximum number of coins to give as change? 6 [Enter] Number of poss ible combinations: 77 Best combination of coins :

M

Focus on Software Engineering: Recursion vs. Iteration

CONCEPT: Recursive algorirhms can a lso be coded with iterative control structures . There are advantages and disadvantages to each approach.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises

i

1139

us uf

Any algorithm that can be coded with recursion can also be coded with an iterative control structure, such as a while loop. Both approaches achieve repetition, but which is best to llse?

Yo

There are several reasons not to use recursion. Rec ursive algorithms are certainly less efficient than iterative algorithms. Each time a function is called, the system incurs overhead that is not necessary with a loop. Also, in many cases an iterative solution may be more evident rhan a recursive one. In fact, the majority of repetitive programming tasks are best done with loops.

az

Some problems. however, arc more easily solved with recurs ion than with iteration. For example, the mathematica l defi nition of the GCD form ula is well-suited for a recursive approach. The QuickSort algorithm is also an example of a function that is easier to code with recursion than iteration.

an

Ri

The speed and amount of memory available to modern computers di minishes the perfo rma nce impact of recursion so much that inefficiency is no longer a strong argum ent against it. Today, the choice of recursion or iteration is primarily a design decisio n. If a problem is more easi ly so lved with a loop, that shou ld be the approach you take. ff recursion resu lts in a bener design, that is the choice you should make.

Review Questions and Exercises

ss

Short Answer

1. What is the base case of each of the recursive functions listed in questions 12.13, and 14?

Ha

2. What type of recursive function do you think would be more difficult to debug, one that uses direct recursion, or one that uses indirect recursion? Why? 3. Which repetition approach is less effi cient, a loop or a recursive function? Wh y? 4. When should you choose a recursive algorithm over an iterati ve algorithm?

ad

5. E?,plain what is likely to happen when a recu rsive function that has no way of stoppmg executes .

m

Fill-in-the-Blank

6. The _ _ _ _ of recursion is the number of times a function ca lls itself.

m

7. A recursive fun ction's solvable problem is known as irs _____ . This causes the recursion to stop.

8.

uh a

9.

recursion is when a function explicitl y ca lls itself. recursion is when functio n A caUs function B, which in turns ca lls

function A.

M

Algorithm Workbench 10. Write a recursive function an a rray.

to

return the number of times a specified number occurs in

11. Write a recursive fu nction to return the largest value in an array.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Recursion

i

Chapter 19

1140

us uf

Predict the Output What is the output of the following programs? 12. linclude <iostream>

using names pace std;

Yo

iot function(intli

int main() {

= 10;

cout «

function(x) «

endl ;

az

int x

return 0; }

Ri

iot function(int num) {

if (num <= 0) return OJ e 1 se

an

return function(num - 1) + num; 13. #include <iostream> using names pace stdj

int main() {

int x = 10;

Ha

void function(int);

ss

}

function (x) ;

ad

return 0 ; }

{

m

void function(int num) i f (num > 0,

uh a

m

{

for (int x

-

0; x < num; x++) « cout ''''' ,. cout « endl; function(num - 1) ;

}

}

14. hnclude <iostream>

M

using names pace std ;

void function (char tl, int , iot) ; int main()

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1141

char names[) = "Adam and Eve"; cout « names « end1; fu nction(names , 0, 13); return 0 ;

us uf

{

i

Review Questions and Exercises

)

void function(char array[ ), int pas , int size)

Yo

{

if (pas < size - 1) {

function(array, pas + 1, size) ; cout « array[pos)i )

az

)

Ri

Programming Challenges 1. Iterative Factorial

Write an iterative version (using a loop instead of recursion) o f the facto ria l func tion shown in this chapter. Test it with a driver program.

an

2 . Recursive Conversion

Convert the followi ng function to one tha t uses recursion.

ss

void sign(int n) {

Ha

while (n > 0) cout « "No parking\n" ; n--; )

Demonstrate the functio n with a driver program. 3. QuickSo rt Template

ad

Create a template version of the QuickSort algo ri thm that will work with any data type. Demonstrate the template with a driver fu nction.

m

4. Recursive Array Sum

m

Write a function that accepts an array of integers and a number indica ting the number of clemcnrs as argLlnlcnrs. T he function should recurs ively calculate rhe sum of all the numbers in the array. Demonstrate the function in a driver program.

5. Recursive Multiplication

uh a

Write a recursive funct ion that accepts two arguments into the parameters x and y. The function shou ld return the value of x times y. Remember, multiplication can be performed as repea ted addition:

M

Solving Ihe Recursive Muhiplicalion Problem

7 * 4

=

4 + 4 + 4 + 4 + 4 + 4 + 4

6. Recursive Power Function Write a fu nction that uses recursion to raise a number to a power. T he func tion should accept twO arguments: the number to be raised and the exponent . Assume that the exponent is a nonnegative integer. Demonstrate the funct ion in a program.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 19 Recursion

1142

us uf

7. Sum of N umbers

Write a function that accepts an integer argument and returns the sum of all the integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function wi ll retu rn the sum of 1, 2, 3, 4, ... 50. Use recursion to calculate the sum. Demonstrate the func tion in a program.

Yo

8. i SHe mbe r Function

Write a recursive Boolean function named iaHember. T he funaion shoul d accept two arguments: an array and a va lue. The function should return true if the value is found in the array, or fa lse if the value is not found in the array. Demonstrate the functio n in a driver progra m .

az

9. String Reverser

10.

maxNode

Function

Add a member function named maxNode

Ri

Write a recursive function that accepts a string as irs argument and prints the stri ng in reverse order. Demonstrate the function in a driver program.

[0

the NumberList class discussed in ch is

an

chapter. T he function sho uld return the largest value stored in the list. Use recu rsion in the fun ction to traverse the list. Demonstrate the function in a driver program.

11. Palindrome Detector

Ha

Able was I, ere I saw El ba

ss

A palindrome is any word, ph rase, or sentence that reads the same forward and backwa rd. H ere are some we ll -known pal indromes: A man, a plan, a can al, Pa nama Desserts, I stressed

Kayak

ad

Write a bool funct ion that uses recursion to determine if a string argument is a palindrome. The function should return true if the argument reads the same forward and backward. Demonstrate the fu nction in a program.

m

12. Ackermann's Function Ackerma nn 's Function is a recursive mathematical algorithm that cao be used to test how well a computer performs recursion. Write a fu nction A(m, oj that so lves Ack-

m

ermann's Function. Use the following logic in your funct ion:

uh a

If m - 0 then I f n = 0 then Otherwise,

return n + 1 r e turn A(m-1, 1 ) return A(m-1, A(m, 0- 1))

Test your function in a driver program that displays the following values: 0)

A(O,

1J

A( 1,

1)

A( 1 ,

2)

A( 1,

3)

A( 2,

2)

A( 3,

M

A(O,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

2)


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1143

i

Review Questions and Exercises

us uf

Serendipity Booksellers Software Development ProjectPart 19: A Problem-Solving Exercise Previously you completed func tions fo r displaying a series of inventory reports: repListing

Yo

repWholesale repRetail repQty repCost repAge

az

Modify your program 50 it uses the QuickSort algorithm to sort the data stored in the linked list of BookOata structures before the reports are printed. The book data should be

M

uh a

m

m

ad

Ha

ss

an

Ri

sorted by ISBN nu mber.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

o

az

o

Definition and Applications

20.2

of Binary Trees Binary Search Tree Operations

20.3

Template Considerations for Binary Search Trees

ss

an

20.1

Ri

TOPICS

Ha

Definition and Applications of Binary Trees CONCEPT; A binary tree is a nonlinear linked structure in which each node

ad

may point to two oth er nodes, and every nod e bur the root node has a single predecessor. Binary trees exped ite [he process of searching large sets of data.

m

A standard li nked list is a linear data structure in which one node is linked to the next. A binary tree is a nonli nea r linked srruct ure. It is nonli near beca use each node can paim ro two orher nodes. Figure 20-1 illustrates the organization of a binary rree.

M

uh a

m

The data structure is ca lled a cree because it resembles an upside-down tree. It is ancho red ar rhe rap by a tree pointer, which is like the head pointer in a standard linked list. The first node in th e list is called the root node. The root node has pointers to two other nodes, which are ca lled children, or child nodes. Each of the children has its own set of twO pointers, and can have its own children. Notice [hat not all nodes have twO childeen. Some point to only one node, and some poim ro no other nodes. A node that has no children is called a leaf node. All poimers that do nOt poin t to a nod e a rc set to NULL.

1145

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 20

1146

Binary Trees

us uf

i

Figure 20-1

Ri

az

Yo

,," """.,

NULL

ss

NULL

an

NULL

NULL

NULL

Ha

Binary trees can be div ided into subtrees. A subtree is an entire branch of the tree, from one particular node down. For exampl e, Figure 20-2 shows the left subtree from the root node of the tree shown in Figure 20-1.

m

m

ad

Figure 20-2

Left

...-

,/

,/

uh a M

Subtre~

I

NULL

NULL

/

I ,/

\

,/ '-NULL

NULL ./

NULL

NULL

'-

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 20.1 Definition and Applications of Binary Trees

i

1147

us uf

Applications of Binary Trees

Yo

Searching any linear dara structure, such as an array or a standard linked list, is slow when the strucrure holds a large amount of dara. This is because of the sequential nature of linear dara structures. Binary trees are excellent data structures for searching large amounts of data. They are commonly lIsed in database applications to organize key values that index database records. When llsed to fa cilitate searches, a binary tree is called a binary search tree. Binary sea rch trees are the primary focus of this chapter. Data are stored in binary search trees in a way th ar makes a binary search simp le. For examplc::, look at Figu re 20-3.

--

ad

B

Ha

F

m

NULL

ss

an

Ri

az

Figul"e 20-3

NULL

NULL

NULL

NULL

M

uh a

m

The figure depicts a binary search t.ree where each node stOres a letter of the alphabet. Notice that the rOOt node holds the letter M. T he left child of the root node holds the letter F, and the right child holds R. Va lues are stOred in a binary search tree so that a node's left ch ild holds data whose va lue is less than the node's data, and the node's right ch ild holds data whose vallie is greate r than the node's da ta. This is true for all nodes in the tree that have children.

It is also true that all the nodes to the left of a node hold values less than the node's value. Likewise, all the nodes to the right of a node hold values that are greater than the node's data. When an appl ication is searching a binary tree, it sta rts at the root node. If the root node docs not hold the search val ue, the applica tion branches ei ther to the left or right child, depending on whether the search value is less than or greater than the value at the root node. This pl'ocess continues until (he va llie is found. Figure 20-4 illustrates the search pattern for finding the letter P in the binary tree shown.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Binary Tr@@s

i

Chapt@r 20

1148

us uf

Figure 20-4

1

_ _

'f '

,

r-----'"~~~.~~T:~~_~r

M

"

Yo

I

I

I

, I

Ri

R

2

az

I

I

F

I

I>-

\ 3 NULL

NUll

NUl l

20.2

Desc ribe the difference between a binary tree and a standard linked lise What is a root node?

20.3

What is a child node ?

20.4

What is a leaf node?

20.5

What is a subt ree?

20.6

Why arc binary trees suitable fo r algorithms tha t must search large amounts of data?

m

m

ad

20.1

ss

~ Checkpoint

NULL

NULL

Ha

NULL

'"p

an

B

uh a

Binary Search Tree Operations

M

CONCEPT: There are man y operations that may be performed on a bin ary search tree. In this section we will discuss creating a binary search tree and inserting, finding, and deleting nodes. In this section you will learn some basic operations that may bc performed on a b inary search tree. We will study a simple class that implements a binary tree for storing integer values.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1149

i

20.2 Binary Search Tree Operations

us uf

Creating a Binary Tree

We will demonstrate the fundamental binary tree operations using a simple ADT: the IntBinaryTree class. The basis of our binary tree node is the following struct decla ration: struct TreeNode {

,

Yo

}

int va l ue ; TreeNode *left; TreeNode *right;

az

Each node has a value member fo r storing its imeger data, as well as left and rig ht po imers. The struct is implemented in the class declaration shown here:

Contents of IntBinaryTree. h

II Specification file for the IntBinaryTree class 'ifndef INTBINARYTREE H

Ri

1 2 3

'define INTBINARYTRSE H

{

int value; TreeNode *left; TreeNode "right;

10 11

12

13 14 15

} ;

TreeNode *root;

16

18 19 20 21 22

II Private member functions void insert(TreeNOde *&, TreeNode *&); void destroySubTree(TreeNOde * ); void de~eteNode( i nt. TreeNode *&); void makeDeletion(TreeNode *&); void displaylnOrder(TreeNOde *) canst; void d i splayPreOrder(TreeNode *) canst; void displaypostOrder{TreeNOde *) canst;

m

23

II Pointer to the root node

ad

17

II The value in the node II Pointer to left ch i ld node II Pointer to right child node

ss

9

class IntBinaryTree { private; struct TreeNode

Ha

5 6 7 8

an

4

24

m

25 26

uh a

27 28 29

public ; II Constructor IntBinaryTree{) { root = NULL;

M

30

31

II Destructor

32 33

-IntBinaryTree() { destroysubTree(root) ; }

34 35 36 37 38

II Binary tree operations void insertNode(int)i bool sea rchNode(int); void remove(int);

39

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 20 Binary Trees

41 42 43 44

i

void displayInOrder() canst displayInOrder(root); {

40

us uf

1150

}

void displayPreOrder() const displayPreOrder(root): {

}

45 47

48

) ;

49

tendif

)

Yo

void displayPostOrder() canst { displayPostOrder(root) ;

46

az

The root poi mer will be used as the tree poimer. SilTl1lar to the head pointer in a linked lisr, roor will poim ro the first node in rhe tree, or to NULL if the tree is empty. It is initialized in the co nstructor, which is declared inli ne. The destructor calls destroySubTree, a private member function that recursively deletes all th e nodes in rhe tree.

Ri

Inserting a Node

27 28

void IntBinaryTree : : i nsertNode(int nurn) {

II Pointer to a new node .

TreeNode *newNode;

30 31

II Create a new node and store num in it.

ss

29

newNode = new TreeNode; newNode - >value = num; newNode - >left = newNode->rlght = NULL:

32

33 34 3S

Ha

Inserting a Node in a Binary Tree

an

The code to inseer a node into the tree is fairly straightforward. The public member funcrion insertNode is ca lled with the number to be inserted pa ssed as all argument. The code for the function, which IS in IntBinaryTree. cpp, is shown here:

36

II Inse rt the node. insert(root, newNode):

37 }

ad

38

m

m

Fi rse, a new node is allocated in line 32 and its address sto red in the local pointer variable newNode. The value passed as an argument is stored in the node's value member in line 33. The node's left and r-ight child po imers are set to NULL in line 34 because all nodes must be inserted as leaf nodes. Nexr, the private member funcrion insert is called in line 37. Notice that the root pointer and the newNode pointer arc passed as arguments . The code for [he insert function is shown here: 12

void IntBinar-yTree: : inser-t(TreeNode *&nodePtr, TreeNode *&newNode)

13

{

uh a

14 15 16 17 18

nodeptr = newNode; I I Insert the node . else i f (newNode- >value < nodePtr->value) insert(nodePtr- >left, newNode); II Search the left br-anch . else inse rt (nodePtr->right, newNode); II Search the right branch .

M

19

20

if (nodePtr == NULL)

}

In general, this function takes a pointer to a su btree and a pointer to a new node as argu mems. It searches for The appropriate location in the subtree to insert the node, and then makes the insertion . Notice the declaration of the first parameter, nodePtr:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1151

i

20.2 Binary Search Tree Operations

us uf

TreeNode *&nodePtr

The nodePtr parameter is not simply a pointer to a TreeNode structure, but a reference to a pointer to a TreeNode structure. This means that any action performed on nodePtr is actually performed on the a rgument that was passed into nodePtr. The reason for this will be explained momentarily.

if (nodeptr == NULL) nodePtr = neWNode:

Yo

The i f statement in line 14 determines whether nodeptr points ro NULL:

II Insert the node.

az

If nodePtr points to NU LL, it is at the end of a branch and the insenion point has been found. nodePtr is chen made to poine to newNode, which insens newNode into the tree. This is why the nodePtr pa rameter is a reference. If it weren't a reference, this function would be making a copy of a node point to the new node, not the actual node in the tree. if

statement in line 16 executes:

Ri

If nodePtr doesn't point to NULL, the following else

else if (newNode->value < nodeptr->value) insert(nodePtr-> l eft, newNode); II Search the left branch.

an

If the new node's va lue is less than the value poinred to by nodeptr. the insertion point is somewhere in the left subtree. If this is tbe case, the i nsert function is recu rsively called in line 17 with nodePtr->left passed as the subtree a rgument.

ss

If the new node's val ue is not [ess than the value pointed to by nodePtr, the else statement in lin e 18 executes:

Ha

else insert(nodePtr->right, newNode);

II Search the right branch.

The else statement recursively ca ll s the insert fun ction ca lled with nodeptr->right passed as the subtree argument.

ad

Program 20 -1 demonstrates these functions.

Program 20-1

II This program builds a binary tree with 5 nodes .

2

i include <iostream> finclude" IntBinaryTree . h ,. using namespace std;

3 4

m

1

m

5

int main() { IntBinaryTree tree;

uh a

6 7 8 9

cout ÂŤ "Inserting nodes. "; tree.insertNode(5)i tree.insertNode(B); tree.insertNode(3)i tree.insertNode(12); tree.insertNode(9); cout ÂŤ "Done . \n" j

10

11

12

M

13 14

15

16

17

18 19

return

OJ

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 20

Binary Trees

i

1152

us uf

Figure 20-5 shows the structure of the binary tree built by Program 20-1.

Yo

Figure 20-5

az

5

NULL

an

NULL

Ha

ss

NULL

Ri

8

3

9

NOTE: T he shape of the tree is determined by the order in which the va lues are

inserred. The root node in the diagram above holds the value 5 because that was the first value inserted. By stepping through the functio n, you can see how the othcr nodes came

~

appear in their depicted positions.

m

to

m

()

NULL

ad

NULL

NOTE: If the new value being inserred into thc tree is eq ual to an existing value, the

uh a

~L-_i_n_,e_r_t1_'o_n__'I_g_o_r_ir_h_m__in_,_e_r_r'__ir_t_o_t_h_e_r_i_g_h_t_o_f_t_he__e_x_i,_t_in_g__v,_I_"_e_, ______________________-'

M

Traversing the Tree There are three common methods for traversing a binary tree and processing the value of each node: in order, preorder, and postorder. Each of these methods is best implemented as a recursive function. The algorithms are descri bed as follows:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1153

lnorder tratJersal

us uf

i

20.2 Binary Search Tree Operations

1. The current node's lefr subtree is traversed. 2. The currenr node's data is processed. 3. The current node's right subtree is traversed.

Preorder tratJersai 1. The currenr node's data is processed 2. The current node's left subtree is traversed. 3 . The current node's right subtree is traversed.

Postorder traversal 1. The current node's left subtree is rrave rsed.

az

2. The current node's right subtree is traversed. 3 . T he current node's data is processed.

Yo

void displaylnOrder() const disp l aylnOrder(root); }

an

void displayPreOrder() const displaypreOrder(root); }

Ri

The IntBinaryTree class can display all the va lues in the tree using all three of these algorithms. T he algorithms are initiated by the following inline public member functions:

void displaypostOrder() const ( d isplayPostOrder(root); }

Ha

ss

Eac h of the pub lic member functions calls an overloaded recursive private member function, and passes the root poimer as an argument. The recursive functions, which are very simple and straightforward, are shown here: 149

//**************************** ** ************** ********* ** ** *******

150

II The displaylnOrder member function displays the values II in the subtree pointed to by nodePtr, via inorder traversal.

*

* 11** *************** *********** ************ ******* *** ** ***** *******

154

void IntBinaryTree :: displaylnorder(TreeNOde *nodeptr) const { if (nodePtr) { displaylnOrder(nodeptr->left); cout « nodeptr->value « endl; dis playlnOrder(nodePtr- >right);

m

155 156 157 158 159

ad

151 152 153

m

160

161 162

M

uh a

163 164 165

166 167 16B 169 170 1 71

172 173

174

} //******* ******************* *********** *** ************** ********** II The displayPreOrder member function displays the values * // in the subtree pointed to by nodePtr, via preorder traversal. * //**** *********************** ***** ******************************** void IntBinaryTree : :displaypreOrder(TreeNade *nodePtr) const { if (nodePtr ) { cout « nodeptr - >value « e ndl; displayPreOrder (nodeptr - >left) ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

175 17 6 177 178

Binary Trees

i

Chapter 20

displaypreOrder(nodePtr->right);

us uf

1154

}

}

179

180

II The displayPostOrder member function displays the values • /1 in the subtree pointed to by nodePtr, via postorder traversal.-

11·--*-···_-----_···_----_·_·_--_·_·_-·-----_· __ ·_·_-- ************

184

void IntBinaryTree::displayPastOrcter(TreeNOde *nodePtr) const

185

{

186

if (nodePtr)

187

{

Yo

161 182 183

displayPostOrder (nodePtr->left) ;

189 190 191

displaypostOrder( nodeptr->right) ; cout « nodeptr->value « endl; }

Ri

192

az

188

)

Program 20-2, which versal methods.

IS

a modification of Program 20-1, demonstrates each of the tra-

an

Program 20-2

II This program builds a binary tree with 5 nodes.

II The nodes are displayed with inorder, preorder, II and postorder algorithms , 'include <iostream> Hnclude" IntBinaryTree. h" using namespace stdi

7

8

int main()

9

{

Ha

3 4 5 6

ss

1

2

IntBinaryTree tree ;

12

II Insert some nodes. cout « "Inserting nodes . \n" ; tree.insertNode(5)i tree.insertNode(B)i tree . insertNode(3); tree . insertNode(12)i tree . insertNode(9) ;

ad

10 11

m

m

13 14 15 16 17 18 19 20 21 22 23

j

uh a

II Disp l ay inorder . cout « "Inorder traversal: \n" tree.displaylnOrder()i

II Displ ay preorder. cout« "\nPreorder tr a ver sal;\n"; tree . displaypreorder()i

24

M

25 26 27 28 29 30 31

32

I I Display postorder . cout « "\nPostorder traversal:\n"j tree,disp1aypostOrder(); return OJ

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1155

us uf

i

20.2 Binary Search Tree Operations

Program Output

Inserting nodes. I norder traversal : 3 5

Yo

8 9 12

Preorder traversal :

az

5 3 8

12 9

Ri

Postorder traversal: 3

9

12

ss

Searching the Tree

an

8 5

Ha

The I ntBinaryTree class has a publ ic member function, searchNode, that returns true if a value is found in the tree, or false otherwise. The function simp ly starts at the root

node and traverses the ttee until it finds the seatch value, or runs out of nodes. The code is shown here. 63

bool IntBinaryTree::searchNOde(int num)

64

{

66

67

6.

{

70 71

m

72 73 74

uh a

~

root :

while (nodePtr)

m

69

TreeNode *nodeptr

ad

65

if (nodePtr - >value == nurn) return true; else if (nurn < nodePtr->valuej nodept r nodePtr->left : else nodeptr = nodePtr->right;

75

76 77

return false; )

M

Program 20-3 demonstrates this function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

20~ J,

us uf

Program

i

Chapter 20 Binary Trees

1156

1 II This program builds a binary tree with 5 nodes. II The SearchNode function is demonstrated.

2

6 7

int main()

8

{

IntBinaryTree tree;

II Insert some nodes in the tree , COllt « "Inserting nodes. \n "; tree.insertNode ( 5) ; tree.insertNode(B)i tree.insertNode(3); tree. insertNode{1 2); tree.insertNode(9)j

12

13

14

15 16

17 18 19

II Search for the value 3. if (tree.searchNOde{3» cout« "3 i s found in the tree.\n·'; else cout « "3 was not found in the tree . \n " j

an

20 21 22

23

ss

24

27

28 29

30

Ha

II Search for the value 100 . if (tree.searchNOde(lOO» cout « "100 is found in the tree.\n" ; else cout « "100 was not found in the tree. \n " ; return 0;

25 26

}

Program Output

Inserting nodes.

ad

31

az

9 10 11

Ri

4

Yo

5

'include <iostream> #include" IntBinaryTree. h" using names pace std;

3

3 is found in the tree.

m

100 was not found in the tree.

m

Deleting a Node

uh a

Deleting a lea f node is not difficult. We simpl y find its parent and set the child pointer that links to it to NU LL, then free the node's memory. Bur what if we wanr to delete a node that has child nodes? We must delete the node while at the same time preserving the subtrees that the nod e links to.

Deleting a

Node from a

M

Binory Tree

There are two possible si tuations to face when deleting a nonleaf node: the node has one child, or the node has two children. Figure 20-6 illuslrates a tree in which we are about to delete a node with one subtree.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1157

i

20.2 Binary Search Tree Operations

us uf

Figure 20-6

~

~

~

NULL

~

Ri

NULL

NUll.

NUll

NULL

an

NUll.

Cf1\

az

~Cf1\

Yo

-

This node will be deleted

ad

Ha

ss

Figure 20+7 shows how we will link the node's subtree with its parent:

- - -1":'1'f] ~ __ J!....J...~J

m

~

I

I

\ \

.; , --'-r::==::,

~

M

uh a

m

NUli

NULL

NULL

NULL

NULL

The problem is not as easily solved, however, when the node we are about to delete has two subtrees. For example, look :H Figure 20+8:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Binary Trees

i

Chapter 20

1158

Yo

us uf

Figure 20-8

~:---r;ffl .. __ ..lL-~J ,, \

,---r.;:==::i"

NULL

Ri

NUU.

az

This node will be deleted

NUll

NULL

an

NULL

NULL

NULL

Ha

resu lt is shown in Figure 20-9.

ss

Obviously, we cannot a n3ch borh of the node's subtrees [0 its parem , so th ere mUSt be an alternative solution. One way of addressing this problem is to attach the node's right subtree to the parem, [hen fi nd a position in rhe right subtree to attach the left subtree . The

m

ad

Figure 20-9

This node wi ll be deleted

'-----"--] I_ I"""'" ~ jl~ ! ~\

uh a

m

'--~. I

__

,

~

~

M

,--+-=::1

NULL

,,

NUll

NU LL

NULL

NULL

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

20.2 Binary Search Tree Operations

i

1159

84

void IntBinaryTree::remove(int num)

85

(

86

us uf

Now we wil! see how this action is implemented in code. To delete a node from the IntBinaryTree, call the public member remove . T he argument passed to the function is the val ue of the node you wish to delete. The remove member function is shown here:

deleteNode(num , root); )

Yo

87

The remove member function calls the cteleteNocte member function. It passes the value of the node to delete and the root poi mer. The deleteNode member function is shown here:

az

void IntBinaryTree :: deleteNOde(int num , TreeNode *&nodeptr) { if (num < nodePtr - >value) deleteNOde(num, nodePtr->left) i else if (num > nodePtr->value) deleteNOde(num, nodeptr-> right); e l se makeDeletion(nodePtr); }

Ri

95 96 97 98 99 100 101 102 103

an

Notice that this function's arguments are references to poin ters. Like the insert function, the deleteNode function mUSt have access ro an acrual pointer in rhe tree. YOli will see why momentarily.

ss

The deleteNode function uses an if/e l se if statement. The first parr of the statement is in lines 97 and 98 :

Ha

if (num < nodePtr->value)

de l eteNode(num, nodePtr->left);

ad

This code compares the parameter num with the value member of che node that nodePtr points to. If num is le~s, then the value being searched for will appear somewhere in nodeptr's left subtree (if it appears in the tree at all). In this case, rhe deleteNode function is recursively called with num as the first argument and nodePtr - >left as the second argument.

If num is nOt less than nodePtr->value, the else if in li nes 99 and 100 statement is executed:

m

else if (nurn > nodePtr->value) deleteNOde(num , nodeptr->ri9ht);

M

uh a

m

If num is greater than nodePtr - >value, then the value bei ng searched for will appea r somewhere in nodePtr'S right subtree (if it appears in the tree at all). So, the deleteNode func tion is recursively called with num as the first argument, and nodePtr->right as the second argument.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 20

Binary Trees

i

1160

us uf

If num is eq ual to nodePtr->value, then neither of the i f statements will fi nd a true condition. In this case, nodePtr points to the node that is to be deleted, and the tra iling else in lines 10 ] and 102 will execute: else

makeDeletion(nodePtr)i

Yo

The trailing else statemem calls the makeDele tion func tion, and passes nodePtr as its argumem. The makeDeletion function actually deletes the node from the tree, and must reattach the deleted node's subtrees as shown in Figure 20-9 . T he refore, it must have access to the actual poimer, in the binary tree, to the node that is being deleted (not JUSt a

az

copy o f the pointer). This is why the nodeptr parameter in the deleteNode function is a reference. It must pass to makeDe l etion tbe actual pointer, in the bina ry tree, to the node that is to be deleted. T he makeDeletion function 's code is as follows: void IntBinaryTree :: makeDeletion(TreeNode *&nodePtr) {

Ri

112 113

// Define a temporary pointer to use in reattaching II the le f t subtree. TreeNode *tempNodePtr ;

114

115 116 117

if (nodePtr == NULL) cout ÂŤ "Cannot delete empty node . \n " i else if (nodePtr- >right == NULL) { tempNodeptr = nodePtr; nodePtr = nodePtr - >lefti 1/ Reattach the left child . delete tempNodePtri } else if (nodePtr - >left == NULL)

an

118 1 19 120 121 123 124

125 126 127 1 28

{

tempNodePtr = nodePtr:

nodeptr

129 130

II Reattach the right child.

ad

}

/1 If the node has two children . else

132 133 134

{

m

m

135 136 137 138 139 140

uh a

141 142 143

M

= nodePtr->right ;

delete tempNodePtri

131

144 145 146 147

Ha

ss

122

II Move one node to the r ight . tempNodePtr = nodePtr->right j // Go to the end l eft node . while (tempNodePtr- >left) tempNodePtr = tempNodePtr- >left: II Reattach the le f t subtree . tempNodePtr->1eft = nodePtr- > leftj tempNodePtr = nodePtri 1/ Reattach the right subtree. nodeptr ~ nodeptr- >righti de l ete tempNodePtri

} }

Program 20-4 demonstrates these functions.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1161

Program 20-4

1 II This program builds a binary t ree with 5 nodes. 2 II The DeleteNode fUnction is used to remove two of them .

int main() {

9 10 11 12 13 14 15 16

17 18 19

20 21

Yo

7 8

IntB i naryTree tree ;

II Insert some values into the tree. cou t « "Inserti ng nodes . \n" ; tree . i ns ertNode(5); tree . insertNode(8); tree . insertNode(3); tree.insertNode(12); tree . insertNode ( 9) ;

II Display the values. cout « "Here are the values in the tree : \o" : tree , displayInOrder() :

22

26 27 28 29

II Delete the value 12. cout « "De l eting 12 .. . \0" ; t r ee . remove(12);

Ha

30

II Display the values. cout « "Now, here are the nodes : \n" ; tree.d i splayInOrder()i retur n 0 ;

ad

31 32 33 34

ss

25

II Delete the value 8 . cout« "Deletiog 8 ... \0"; tree.remove(S);

23 24

az

5 6

8include <iostream> #include "IotBinaryTree . h" using namespace std ;

Ri

4

an

3

us uf

i

20 .2 Binary Search Tree Operations

m

35

Program Output

3

5

uh a

8 9

m

Inserting node s . Here are the values in the tree :

M

12 Deleting 8 . . . Deleting 12 .. . Now , here are the nodes : 3 5

9

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 20

Binary Trees

us uf

i

1162

For your reference) the entire contents of IntBinaryTree file are shown below.

Contents of IntBinaryTree. cpp II Implementation file for the IntBinaryTree class 'include <iostream>

Yo

1 2 3 4 5 6 7

iinclude "IntBinaryTree. h" using names pace std;

·*·_-----_·_--------_··*·---*-

11**··_····*****-··**· __ ********* II insert accepts a TreeNode pointer and a pointer to a node. *

az

S II The function inserts the node into the tree pointed to by * 9 II the TreeNode pointer. This function is called recursively. *

10 11***-*---*--------*--------**-*----_·_--------------- *********

11

Ri

12 void IntBinaryTree :: insert(TreeNode *&nodePtr, TreeNode *&newNode) 13 {

14

if (nodePtr

15

nodePtr = newNode; II Insert the node. else if (ncwNode->value < nodePtr->value) insert(nodePtr - >left. newNode); II Search the left branch. else II Search the right branch. insert(nodePtr - >right, newNode);

NULL)

an

16 17 18 19

==

and passes it to the insert function .

Ha

24 II

ss

20 } 21 22 11**************************************************** ****** 23 /1 insertNode creates a new node to hold num as its value, *

26

27 void IntBinaryTree::insertNode(int nurn)

29

TreeNode *newNode;

30

ad

28 {

31

/1 Create a new node and store nurn in it. newNode : new TreeNode; newNode->value ; num; newNode->left = newNode->right = NULL;

m

32 33 34

II Pointer to a new node.

35

m

36 37

/1 Insert the node. insert(root, newNode);

uh a

3. } 39 40 //***********************-*************************** 41 // destroysubTree is called by the destructor. It *

M

42 II deletes all nodes in the tree. 43 //*************************************************** 44

45 void IntBi n aryTree :: destroySubTree(TreeNode *nodePtr) 46 { 47 if (nodePtr)

4.

49 SO

{

if (nodePtr->left) destroySubTree(nodePtr - >left);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1163

51 52 53 54

us uf

i

20.2 Binary Search Tree Operations

if (nodePtr->right) destroySubTree{nodePtr->right): delete nodePtr; )

TreeNode ·nodePtr

66 67

while (nodeptr)

71 72 73 74 75 76

if (nodePtr- >value == num) return truei else if (num < nodePtr->value) nodeptr nodePtr->lefti else nodePtr->right; nodePtr

an

{

)

return falsei

77 )

Ha

78

rooti

ss

68 69 70

~

Ri

64 { 65

az

Yo

55 ) 56 57 //***.* ••• ** ••••• **** •••• *** ••••• ** ••••••• *** ••••••••••• 58 // searchNode determines whether a value is present in • 59 // the tree. If so, the funct i on returns true . • 60 // Otherwise, it returns false . • 61 //*** •• ***** •• *******.*******.**************** •• ****.*** 62 63 bool IntBinaryTree::searchNOde(int num)

79 //***.******.**************** •• ***** ••• ********* 80 // remove calls deleteNode to delete the • 81 // node whose value member is the same as num . * 82 //* ••• ******.*******.*** •• ******** ••••••••••••• * 83

85 {

86 87 )

deleteNOde(num , root):

m

88 89

ad

84 void IntBinaryTree : :remove(int num)

90 //.* ••••• * ••••••••••••••••• * ••••••• *** •••• * •••

m

91 /1 del eteNode deletes the node whose va l ue 92 /f member is the same as num.

• *

93 fl*******·****·*-*_·*- •• *---***********_.*****

uh a

94

M

95 void IntBinaryTree::deleteNode(int num, TreeNode *&nodePtr) 96 { 97 if (num < nodePtr->value) 98 deleteNode(num, nodeptr->left)i 99 else if (num > nodePtr->va1ue)

100 101 102 103 }

de1eteNode(num , nodePtr->right)i else makeDeletion(nodePtr)i

10' 105

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1164

Binary Trees

us uf

i

Chapter 20

107 /1 makeDeletion takes a reference to a pointer to the node • 108 1/ that is to be deleted . The node is removed and the • 109 II branches of the tree below the node are reattached. * 110 //***********************************************************

111 113 { 114

Yo

112 void IntBinaryTree::makeDeletion(TreeNOde *&nodePtr)

115 116

II Define a temporary pointer to use in reattaching /1 the left subtree. TreeNode *ternpNodeptr;

117 118

if (nodePtr

az

120 121 122 123

== NULL) caut « "Connot delete empty node. \n"; else if (oodeptr->right == NULL)

{

tempNodePtr = nodeptr; nodePtr = nodeptr->!efti delete tempNodeptri

124 125

else if (nodePtr->left

127

{

NULL)

tempNodePtr : nodePtr; nodePtr ~ nodeptr - >righti delete tempNodePtri

129 130 131

}

132

II

II

If the node has two children. else

134

{

Ha

133

135

II Move one node to the right . tempNodePtr ~ nodePtr->right ; /1 Go to the end left node. while (tempNodePtr->left)

136 137

138

139

= tempNodeptr- >left;

Reattach the left subtree . tempNodeptr->left = nodePtr->left; tempNodeptr = nodePtr; II Reattach the right subtree. nodePtr = nodePtr->righti delete tempNodePtr:

m

141 142 143 144 145 146

tempNodeptr

II

ad

140

Reattach the right child.

ss

128

==

1/ Reattach the left child.

an

126

Ri

119

m

}

147 148

uh a

149 I/******************************************k**kkk***k***kk*k*k*** 150 II The displaylnOrder member function displays the values * 151 II in the subtree pointed to by nodePtr, via i norder traversal . * 152 11***********k**************************************** ************ 153

M

154 void IntBinaryTree : : displaylnOrder(TreeNode *nodePtr) const

155 { 156 157 158 159 160 161

i f (nodePtr)

{ displaylnOrder(nodePtr->left); cout « nodeptr->value « endl; displayInOrder( nodePtr- >right); }

162 Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN To Read


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

20.3 Template Considerations fo r Binary Search Trees

us uf

i

1165

163

az

Yo

16' 11·········*··*·*······****········*·*·· · ··**** · *·***· *.* •• *** •• • • • 165 II The displayPreOrder member func tion displays the values 166 1/ in the subtree pointed to by nodePtr, via preorder traversal . • 167 11**· · *** ***** ********·*****···******··******·******·· ********.*.* 168 169 void IntBinaryTree : :displaypreOrder(TreeNOde *nodePtrj const 170 ( 171 if (nodePtr ) 172 { 173 cout « nodePtr->value « endl; 174 displayPreOrder (nodeptr - >left); 175 displayPr eOrder(nodeptr->right)i 176 } 177 }

178

Ri

179 /1*. · ··************·**·***** ** ***·*·* ****·***·*** · ·*** * ••• *******. 180 /1 The displayPostOrder member function displ ays the values * 181 II in the subtree pointed to by nodePtr, via postorder traversal . * 182 11····****··*·*·*···*****·*·**·*·* ·* ***·· ·· ***·**··*** ••• ****** • • * 183

Checkpoint

Describe the sequence of events in an inordcr traversal.

20.8

Describe the sequence of events in a preorder traversal.

20.9 20.1 0 20.11 20. 12

Describe the sequence of events in a postorder traversal.

ad

20.7

Describe the steps taken in deleting a leaf node.

m

~

Ha

ss

an

184 void IntBinaryTree : : displaypostOrder(TreeNOde *nodePtr) const 185 { 186 if (nodePtr) 187 { 188 d isplaypostOrder(nodeptr - >left) ; 189 displaypostOrder(nodePtr- >right) ; 190 cout « nodePtr->value « end1 ; 191 } 192 }

Describe the steps taken in deleting a node with one child.

m

Describe the steps taken in deleting a node with twO children.

uh a

Template Considerations for Binary Search Trees

M

CONCEPT: Binary search trees may be implemented as templates, bm any data types used wi th them must support the <. >, and = operators. The acrual implementation of a binary tree template has been left as a Program ming Challenge. When designing your template, remember that any data types stored in the binary cree mUSt support the <, >, and == operators. If you use the tree to store class objects, these operatOrs must be overri dden.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

11 66

Binary Trees

Review Questions and Exercises Short Answer 1. Each node in a binary tree ma y point to how many oth er nodes?

us uf

i

Chapter 20

3. What is a leaf node? 4. What is a subtree? 5. What in itially determines the shape of a binary tree?

Yo

2 . How many predecessors may each node other than the rOOt node have?

az

6. What are t he three methods of traversing a binary tree? What is the difference between these methods?

Ri

Fill-in-the-Blank

7. The first node in a binary tree is called the _ _ __

8. A binary tree node's left and right pointers point to the node's _ _ __

an

9. A node with no ch ildren is called a(n) _ _ __ 10. A(n) _ _ _ _ is an entire branch of the tree, from one particu la r node down.

and _ _ __

Ha

Algorithm Workbench

ss

11. The three common types of traversal wi th a binary tree are _ _ _ _ , _ _ __

12. Write a pseudocode algorithm for inserting a node in a tree. 13. Write a pseudocode algorithm for the inorder traversa l. 14. Write a pseudocode algorithm for the preorder tra ve rsal.

ad

15. Write a pseudocode algorithm for the postorder traversal. 16. Write a pseudocode algorithm for searching a tree for a specified va lue.

m

17. Suppose the following val ues are inserted into a binary tree, in the order given:

m

12,7,9,10,22,24,30,18,3, 14,20

Draw a diagram of the resulting bi nary tree.

uh a

18. How would the va lues in the tree you sketched fo r Question 17 be displayed in an inorder traversal?

M

19. H ow wou ld the vai lles in the tree you sketched for Question 17 be disp layed in a prcorder traversa l? 20. How would the values in the tree you sketched for Question 17 be displayed in a postorder traversal?

True or False 21. T

F

Each node in a binary tree must have at least twO children.

22. T

F

When a node is inserted into a tree, it must be inserted as a leaf node.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1167

i

Review Questions and Exercises

F

Values stored in the current node's left subtree are less than the value stored in the current node.

24. T

F

The shape of a binary tree is determined by the order in which va lues arc inserted.

25. T

F

In inorder traversal, the node's data is processed first, then the left and right

us uf

23. T

Yo

nodes are visited.

Programming Challenges 1. Binary Tree Template

"

az

In this chapter you saw IntBinaryTree, a class that implements a binary trcc of integers. Write a template that will create a binary crcc that can hold values of any data type. Demonstrate the class with a driver program.

Problem

Write a member function, for either the template you designed in Programming Challenge 1 or the IntBinaryTree class, that counts and returns the number of nodes in the tree. Demonstrate the function in a driver program.

an

Node Counter

Ri

2. Node Counter

Solving the

3. Leaf Counter

Ha

4. Tree Height

ss

Write a member function, for either the template you designed in Programming Cha llenge 1 or the IntBinaryTree class, that counts and teturns the number of leaf nodes in the tree. Demonstrate the func tion in a driver program.

ad

Write a member funct ion, for either the template you designed in Programmi ng Challenge 1 or the IntBinaryTree class, that returns the height of the tree. The height of the tree is the number of levels it contains. For example, the tree shown in Figure 2010 ha s three levels.

uh a

m

m

Figure 20-10

M

NULL

NULL

NULL

NULL

NULL

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 20

Binary Trees

us uf

i

1168

Demonstrate the function in a driver program.

5. Tree Width

Yo

Write a member function, for either the template you designed in Programming Challenge 1 or the IntBinaryTree class, that returns the width of the tree. T he width of the tree is the la rgest number of nodes in the same level. Demonstra te the function in a driver program .

6. Tree Assignment O perator and Copy Constructor

az

Design an overloaded assignment ope rator and a copy construcor for either (he template you designed in Programming Challenge 1 or the IntBinaryTree class. Demonstrate them in a driver program.

7. Q ueue Converter

Ri

Write a program t hat stores a series of numbers in a binary tree. T hen have the program insert the values into a queue in ascending order. Dequeue the values and disp lay them on the screen to confirm that they were stored in the proper order. S. Employee Tree

an mteger

a string

ss

Employee 1D Number: Employee Name:

an

Design an Employeelnfo class that holds the following employee information :

Ha

Next, use the template yOll designed in Programmi ng Challenge 1 to implement a bi nary tree whose nodes hold an instance of the Employeelnfo class. T he nodes should be sorted on the Employee ID number. Test the binary tree by inserting nodes with the following information.

m

1021 1057 2487

ad

Empl oyee ID N umber

3769

Bill Witherspoon

JCIll1ifer Twain Sophia Lancaster Debbie Reece George McMu llen Ashley Smith Josh Plemmons

M

uh a

m

1017 1275 1899 4218

N ame John Williams

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises

us uf

i

1169

Your program should allow the user to enter an lD number, then search the tree for the number. If the number is fo und, it should display the employee's name. If the node is not found , it should display a message indica ti ng so.

Yo

Serendipity Booksellers Software Development ProjectPart 20: A Problem-Solving Exercise

Currently, the inventory data are stored by the Reports module in a linked list of InventoryBook objects. For this chapter's assignment, you are to modify the program so it stores the objects in a binary tree.

M

uh a

m

m

ad

Ha

ss

an

Ri

az

The InventoryBook objects should be keyed on the ISBN number. This means your algorithm will use the book's ISBN number to find its insertion point in the tree. You will need to modify the InventoryBook class so it has ove rloaded - =, <, and> operators, or equivalent member functions for allowing compadsons with the ISBN number.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

o

Ri

az

'J

an

Alice is an innovative softw are system that al lows you [Q create 3D animations and comp l1 ter games w hile learning funda memal programming concepts. With Alice you place graphical objects such as people, anima ls, buildings, cars, and so on inside 3D virt ual worlds. T hen you create programming statementS t hat ma ke the objects perform actions. Al ice's dcagand -drop program editor ma kes it easy to create animations with rich interactions between objects.

Ha

ss

This appendix serves as a quick reference for using Alice vers ion 2.0. If you need a complete text that teaches programming using the Alice soft wa re, sec Starting Ollt with Alice: A Visual lntrodllction to Programming, also p ublished by Addison-Wes ley.

Downloading and Installing Alice

ad

Al ice is free soft",Iare, availa ble from Ca rnegie Mellon University. You can download the latest version from http://www.a lice.arg. When you download Alice to your system, you get a file named Alice.zip. There is no installa tion wizard w ith Alice; YO ll simply extract the contems of this file in the location where you want to insta ll the so ftware.

m

When you extract the coments of A lice.zip you will get a fol der named A lice. Inside this fo lder you will find an executable fi le named Alice.exe. Dou ble-click this fi le to ru n Alice.

uh a

m

TIP: You will probably want to create a shortcut to the A lice.exe file on your desktop . Right-click the file a nd then select Send To Desktop (create shortcut) fcom the menu . To start Al ice double-click the shortcut that appears on the desktop.

M

Using the Welcome to Alice! Dialog Box When you stan Alice the splash screen shown in Figure A-l will display for a few seco nds. When (he software is fully loaded you should see the Welcom e to Alice! d ialog box, as sho wn in Figure A-2.

1171

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started with Alice

i

1172

Ri

az

Yo

us uf

Figure A· l Th e Alice splash screen

an

Figure A·2 The Welcome to Alice! dialog box

Ha

ss

~mostAtiAboutAlke

3mllsemenlPark

j

,

UumOe,"o

• o,~

~ Show this tHitloll at stan

NOTE: If you do not see the We/come to Alice! dialog box on your system, then Alice

M

uh a

()

m

m

ad

j

has been configured so it will not display the dia log box at startup, which might be the case in a shared comp uter la b. You can display the dialog box by cl icking File on the menu bar:, and then clicking the New World at Open World ... menu items.

Note that at rhe bottom of the Welcome to Alice! dialog box there is a Show this dialog at start check box. Make sute this check box is checked so the dialog box will be displayed each time you start Alice.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started wi th Alice

us uf

i

Near the rop of [he Welcome to Alice! dialog box you will see a set of tabs labeled Tutorial, Recent Worlds, Temp lates, Examples, and Open a world. The following are brief descriptions of what yo u get when yOll click these tabs :

1173

Yo

Ttttorial- Click this tab and you will see a set of fout Alice worlds that work as tutorials. These tutorial worlds guide you through the bas ic features of Alice. If yOll want to run the tutorials, click the Start the Tutorial button to execute them in order, or select and open any of the worlds individua ll y.

az

Recent Worlds- Click th is tab and you will see thumbn ail images of rhe wo rlds thar were most recently opened on your system. Y Oll can quick ly open any world shown in chis cab by selecting its thumbnail image and then clicking rhe Open butto n. You will nOt sec any worlds listed here if you have not yet opened any worlds.

Ri

Templates-Click this tab and you will see a set of templates that you can use to create a new world. The templates are named dirt, grass, sand, snow, space, and water. Each cempla te gives you a grou nd sudace and a sky colo r.

Examples- Click this tab and you will see th umbnail images of example worlds chat have been created by the developers of Alice.

ss

an

Open a world-Click this tab and yOll will see a dialog box that allows you to open an Al ice world. With this tab you ca n browse your local system Or any attached network drive for Alice worlds. Note that Alice worlds are saved in files that end with the .a2w extension. (T he .a2w extension signifies that the file contains an Alice version 2.0 world.)

Ha

The Alice Environment

ad

In Alice the screen that YOll work with is referred to as the Alice environment. The Alice environment is div ided into the followi ng areas: the Toolbar, the World View Window, the Object Tree, the Detai ls Panel, the Method Editor, and the Events Editor. In addition, the toolbar area provides a crashean ieon and one or more clipboard icons. T he loca tions of these different areas and icons are shown in f igu re A -3. In the figure, SnowLotJe, one of the example worlds, is opened. Brief descri ptions of each area in the Alice environment fo llow:

m

m

To olbar- The wolbar provides a Play bu tton that plays yo ur virtual worl d, an Undo button that undoes the previous operation, and a Redo button that repea ts the operarion that was mOSt rece ntly undone. Trashcan-Next to [he bu ttons on the tool ba r there is a trashca n icon. You delete items by dragging them to the tras hean .

M

uh a

Clipboards-The clipboard provides a place to store a copy of somethi ng. In Alice clipboards you ca n store copies of objects, instructions, methods, and events. To store a copy of an item in a cl ipboa rd, yo u click and drag the item to the clipboa rd. When a clip board conta ins an item, it appears as if it has a white sheet of paper on it. In Figure A-3 the leftmost cl ipboard shows an exa mple. To paste the item that is stored in a clipboard , you click and drag the clipboa rd icon co the location where you want to paste the item. If you want to empty a clipboard, you click and drag it to the crashcan.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1174

Appendix A Getting Started with Alice

us uf

i

By defaul t, Al ice shows only one cli pboard . To change the number of availa ble clipboards you click the Edit menu and (hen click Preferences . On the dialog box that a ppears, you d ick the Seldom Used tab and chen change the number that appea rs next to number of clipboards.

World View Windolv--The World View Window shows a view of you r virtu al worl d. Each

Yo

virtual world has a camera; the World View Window acts as the ca mera's viewfinde r a nd also provides controls for moving and rotating the camera.

Object Tree-The Object Tree holds a list of aJi the objects in the world. Eac h object in the world is represented by a tile , wh ich is simply a small rectangular icon. Tiles are used exten· sivcly in the Al ice environment to represent IHlmerOllS things.

az

Details Panel-The Details Panel shows detailed information a bou t an o bject tha t has been selected in the World View Window or in the Object Tree .

Ri

M ethod Editor- Th e Method Editor is wbere you create methods (a set of instructions that ca uses some action to take place). You create methods by arranging tiles in the Method Editor.

ss

Figure A-3 Parts of the Alice envi ronment

an

Events Editor-An event is some action that takes pJa ce while the world is playing, such as clicki ng the mouse or pressing a key. Alice is able to detect when various evem s take place. You ca n use the Events Editor to spec ify an action th at is to take place when a specific event occurs.

World View window

..~;;;-<-.

~

.

~-

m m

I~~-

~

M

uh a

Details panel

-'" -'" - '" -'"

--~ ~

-:~

-.'~.---

---........ ---- --.. .- -_-......- __ - .- -

____

0_

.

,-- ~

-..

I-'"

_

.

TT I - Clipboards

_. ...--_- . .._. - ++3 JiWI, "( , . I'

r-'

~-

--

I e> ....... _ _ _

.

Q-

.• 10-

ad

Object tree

~

Events Editor

I

.... c:::c::JIh

~~_M

Toolbar

Ha

Trashcan

,

,,...- -..-1,

.

u ... _

..... •

~-~ .

00 ........ 0 0 _

.w

lOOo _

f . . . .. .

. . ..

--

.

Method Editor

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started with Alice

us uf

i

Playing a World

When yOll dick the Play bunon, a sepa rate World Running .. . window appears and the world 's animatioll will play out in that window, For example, Figme A-4 shows the SnowLOlle example wo rld playing.

Ha

ss

an

Ri

az

Yo

Figure A-4 The SnowLove world playing

ad

Notice the roolbar at the top of the World Rut/uing ... window. The following are brief descriptions of the items that appear on the toolba r:

m

Speed Slider Co1ttrol- Th is controls the speed at which the world is played. When the slider is set ro 1 x, the world plays a t tlOl'mal speed. M oving the slider to the right increases the speed lip to 10 times its normal speed. Pa use Bulton-Clicking the Pause button causes the world

[Q

pause.

m

Resume Btlttolt- O nce a world has been paused wnh the Pallse button, you can click the Reslll1'le button to resume playing.

uh a

Restart Bu ttoll-Clicking the Restart burren causes the world co stan playing again.

Stop Buttoll- Clicking the Stop bunon causes the world

to

stop playing and doses the

World Running ... window.

M

117S

Ta k e Picture Button-Clicking t he Take Picture button captures an image from the world and saves it in a fi le. T he dialog box t har appears when you click the Take Picture button reports (he name and path of the file containing the image.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started with Alice

us uf

Creating a New World and Adding Objects to It

i

1176

To create a new world, you click File on the menu bar and then click the New \'(/orid. .. menu item. This displays the Welcome to Altce! dialog box, as shown in Figure A-2 . (By default, this dialog box is also displayed when you sta rt Alice.) Make su re the Templates tab is selected, as shown in Figure A -S.

Yo

The Templates tab shows a set of templates named dirt, grass, sand, snow, space, and water that you can li se to create a new world. When you se lect a template from this dia log box and then click the Open bunon, Alice will create a ground surface and set the color of the sky. For example, Figure A-6 shows a world that was created with the sand template.

water

u, ,

m

ad

S /lOW

Ha

ss

an

Ri

az

Figure A-S The Welcome to Alice! dialog box

m

lhis dialog at start

M

uh a

Fi gure A-6 shows the Add Objects button just below the World View Window. When you click th is button the Alice environment changes to scene editor mode and opens a ga ll ery, as shown in Figure A-7. A gallery is an assortment of different types of objects and is organized into various collections of objects such as anima ls, buildings, furniture, and people. Alice provides two galleries; a local gallery and a Web ga llery. The local gallery is stored on your computer and is installed with the Alice software. It provides a good sampling of object types and should be adequate fo r many of your projects. T he Web gallery is maintained by the creators of Alice and may be accessed if your computer is connected to the Internet. It provides a much more ex[ensive collection of obiecr types than the local gallery.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Appendix A

Getting Started with Alice

Ri

az

Yo

us uf

i

Figure A-6 A w orld created wi t h the sand tem plate

11 77

m

ad

Ha

ss

Figure A-7 Alice in sce ne editor m od e

an

Click the Add Objects button to add objects to the world .

The navigation bar

uh a

m

indicates we are in the local gallery.

M

The collections in the gallery are shown here.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1178

Appendix A Getting Started with Alice

Yo

Ri

az

Figure A-8 Some of the object types in the People collection

us uf

i

Figu re A路7 points out a navigation bar that ind ica tes which gallery and collection is cur路 rendy displayed. Below the navigation bar are thumbnai l images for the collections in the gallery. To open a coll ection and see the object types it contai ns, you click the collection's thumbnail image. For example, one of the collectio ns is named People. It contains various types of people objects, as shown in Figure A-8.

ss

an

O ne way to add an object to the world is to click the thumbnail for that object type. You will then see an information window fo r the object . For example, if you dick the thumbnail for the Coach object type, yo u will see the informa rion window shown, as shown in Figure A-9. Click the Add instance to world button to add an object of this type to the world.

m

m

ad

Ha

Figure A-9 Information window for the Coach object type

Another way to add an object to rhe worl d is to cl ick and drag the thum bnai l for the object

uh a

type into the World View Window. Whe n you release t he mouse bu tton (with the mouse pointer inside the Wocld View Window) an object will be c reated.

After you add an object to a wor ld, you shou ld see a rile [or the object in the Object Tree, as shown in Figure A-l 0. Each objecr in a world has a name, and the object's ti le will show

M

the name that Alice assigned to the objecr. You can rename the object by right-clicking its tile and then selecting rename on the menu that appears.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started with Alice

us uf

i

Figure A-lO An object is added to the world

Yo

An object is added to the world. - - - - - ,

A tile representing

Ri

az

the object is added to the Object Tree.

an

Moving the Camera in the Alice Environment

Ha

ss

The three camera controls shown in Figure A-l 1 appear just below the World View Window. You use these controls to move the camera around in the world and poi nt it in different directions. The control on the left moves the camera up, down, left, and right . The control in the center moves the camera forwa rd and backward, and rorates the camera left and right. The control on the right tilts the camera up and down.

ad

Notice tha t each of the control s shows a set of arrows. You manipulate these controls by click ing and dragging the arrow that points in (he direction thar yotl wa nt to move, rota te, or til t the camera. You can make the camera move fas ter by dragging the mouse pointer away from the center of the ca mera control. The farther you drag the pointer away from the ceorer of the camera control , the faster the camera will move.

m

Figure A-ll Camera controls

m uh a M

ThiS con trol moves the camera forward and backward, and rotates it leH and right.

t ~..-=!~....

I

control moves the camera up, down, left, and right. This

1179

\

This control tilts the camera up

and down.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1180

Appendix A Getting Started with Alice

us uf

i

Selecting Objects

To work with an object in the Alice env Ironment, often yOll first have to selecr rhe objec£. The following are the ways to selecr an object: • Click its tile in the Object Tree • Click the object in the World View Window

az

Yo

When you select an obiecr, a box appears around it in rhe World View Window, as shown in Figure A -12. (On yOllr screen the box wi ll be yellow.) This bounding box indica tes that rhe object is selected. Also, rhe object's rile in the Objecr Tree will appear highl igh ted, as shown in the fig ure.

ss

an

Ri

Figure A-12 The coa ch object is selected

Object Subparts

ad

Ha

Objects are commonly made of other objects, which are referred to as subparts. When a plus sign appears next to an object tile in the Object Tree, it means that the object is made of subparts. For example, look at the Object Tree shown in Figure A-12 and notice that a plus sign appears next to the tile for the coac h ob ject. You can click the plus sign next to an object to expand tht: (ree and see the tiles for the subpa rts. The plus sign then turns into a minus sign, which hides the inner objects when clicked.

m

Figure A-13 shows the Object Tree expanded to revea l that the coach object is composed of numerous subpans . One of these subpans, the head, is selected.

m

Properties

uh a

Eac h object in an Alice world has properties, which arc val ues tha t specify the object's characteristics. Once you have placed an object in an Alice world, you ca n adjust its propen ies until it has the characterisrics you desire. To cha nge an o bject's property you perform the following steps:

M

• Selecc rhe object • In the Details Panel select the properties ra b, as shown in Figure A-14 • Change the val ue of the desired property (to change a property's va lu e, click the down-arrow [hu r appears nexr w rile propeny's value)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started with Alice

us uf

10 rlghlleg

8

fCOfO(ll J'9Ief1LII1J

8

;10'';'''.",

Yo

8 ..

i

Figure A-13 An object subpart selected

This subpart -f----<~' lO_ is selected.

az

[() chestPIMe

~ [() whistle

8 .. !O IeftArm

) O hand lO,ighIAfm

Ri

8

, IOItiJoId

Ha

ss

I'

an

Figure A-14 Prope rties dis played in the Deta ils Panel

ad

- .-

m

Primitive Methods

uh a

m

A method is a set of instructions that ca uses some action to take place. In Alice all objects have a common ser of built-in methods for performing basic actions . These methods, which are known as primitive methods, cause objects CO move, rum, change size, and do other fundamental operations.

M

1181

Whi le yo u are crea ting an Alice world yOlI can immediately execu te an objeer's primitive methods by right-clicking the objeci in [he World View Window or the objecr's tile in the Object Tree. Then you select methods from the menu that appears. Another menu appears showing a list of methods that you can immediately exec ute in the World View Window. Figure A-15 shows an example of these menus. Table A-I describes each of rhe primiti ve methods shown on the menu .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

118 2

Appendix A Getting Sta rted with Alice

,~

capI.. epos,

--_.......-

az

-.

c-a 1lll1I1IIDOIIkK* .. Ulls

Yo

us uf

i

Figure A-15 Selecting a pri mitive method

...... _ 1 0

-_. --1MnIY_

IOWllld

......,,_~fl'llRt

Ri

IIl.oqI IIfIenl 10

""""Vturnlofaca

~1IM1IOk1Ia/f"""lo

an

...... SIIIt.... to ~M'I~lo

...... set IfeIkIe 10 HI ,1m 1,><1..,10

Table A-l Primitive methods

Ha

ss

~

Description

move

This method causes the object to move up, down, left, right, forward, or backward. You speci fy the direction and distance that you want the object to move.

ad

Method Na me

uh a

resize

m

roll

m

turn

think

M

play sound

T his method causes the object to rum tOward the left, right, forward, o r backward. You specify the amount you want the object to turn in

revolutions. This method causes the object ro roll toward the left or the right. YOLl specify the amount you want the object to roll in revolutions. This method changes the object's size by a specified amount. This method causes a cartoon-like speech bubble containing a message to be displayed, as if the object were saying the message. This method causes a cartoon-like thought bubble co ntaining words to be displayed, as if the object were thinking the words. This method plays a sound. You can specify one of the sou nds that Alice provides or you can import any MP3 or WAY file. (continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started with Alice

us uf

i

Table A-l Primitive methods (continued) Description

move to

This method causes the object to move to another object. When the method completes, both objects' center points wi ll be in the same location.

move toward

This method causes the object to move in the direction of anNher object. You specify the distance to move in meters. T his method causes the object to move away from another object. YOLl speci fy the distance to move in meters.

Yo

Method Na me

move away from

This method orients the object in the Same direction as another specified object. When this method executes the object will turn so its up, right, and forward axes are aligned with the axes of the specified object. This method ca uses the object to turn so it is facing anothe r object. This method is similar to the turn to face method, except the object will be tilted so its forward axis is "aiming " at the specified object's center poim.

az

orient to

Ri

turn to face point at

This method sets the objecr's point of view to that of another object. It is commonly used with the camera to move it to the location of another object, and give a view from that object's po im of view. Alice allows you to position an object and its subpa rts in a certain way and then capture tha t as a pose. T his method causes [he object to assume a pose that was previously captured.

an

set po i nt of view to

ss

set pose

This method makes the object "stand up" by aligning the object's up axis wi th the world's up axis.

set color to

This method sets the object's color property to a specified COIOf, making the object appear in that color. This method scts the object'S opa city property, which determines the object's transparency. You set thi s prope rty to some value between 0 percent and 100 percent, where 0 is completely invisible and 100 is completely opaque.

Ha

stand up

m

m

set vehicle to

ad

set opacity to

uh a

set skin tex.ture to

M

set fillingStyle to

1183

This method sets the object's vehicle property. The vehicle property coup les the object with another object. When the other object moves, this object moves with it. ThIS method sets the object's skin texture property. The skin textu r e property specifies a graphic image to be displayed on the object.

The fillingStyle property determines how the object is displayed. It has three setti ngs: solid, wireframe, and points. The default setting is sol id , which causes the object ro be displayed as a solid . When the fillingStyle property is set to wireframe, the object is displayed as a wire skeleton that you can see through. When the filli ng Style property is set to points, the obiect is displayed as a set of points.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1184

Appendix A Getting Started with Alice

us uf

i

Most of the primit ive methods requi re that you specify additiona l pieces of information , For example, the move method causes the object to move, and it requires that you specify two pieces of info rmation: a direC[ion and an amount. These p ieces of information are known as arguments-pieces of information that a method requ ires in order for it to execute,

Yo

Deleting Objects

You can delete an object in an Alice world by performing any of the follow in g operations:

Ri

az

• Right-click the object in the World View Window and rhen select delete from the menu that appears • Right-click the object's tile in the Object Tree and then select delete from the menu that appea rs • Click and drag the object's tile from the Object Tree to the trashcan

Modifying Objects in Scene Editor Mode

ss

an

When you click the Add Ob;ects bunon, which appears below the World View Window, Alice goes inro scene editor mode, in wh ich you can use the mOllse to modify the objects in your Alice wodd. For example, you can use the mouse to move objects, resize objects, rotate objects, and copy objects. Figure A-16 shows the location of the mouse mode buttons, which determine the action that can be performed with the mouse.

Ha

Figure A-16 Location of the mouse mode buttons

_

0 __ otoI<1<f' ....

IIH1,il.§JaJ§J~

,

O llflea_

buttons

M

uh a

m

m

ad

Mouse mode

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started with Alice

1185

us uf

t::s I Move Freely-

i

Figure A~17 shows the purposes of the bu ttons. The' fol lowing are brief descriptions o f each:

When this button is selected the mouse can be used to move an object

Yo

freely in the world. Here are the actions that you ca n perform: - To move an object horizontally within the world you simply click and drag it To move an object stra ight up or down, you hold down the [Sl1ift] key while clicking and dragging the object To rotate an object left or right, yo u hold down the [elrl ) key while clicking and dragging the object To tumble an object (rotate it left, right, forward, backward, or any combination of these directions), you hold down the [etrl) and [Shiftl keys whlle clicking and dragging the object

az

@n Move Up and Down-When rhis button is selected you can move an object straight up or srraight down by clicking and dragging the object. .mI Tum Left and Right- When this button is selected you can rotate an object toward ~

Ri

the left or the right by clicking and dragging the object.

Turn Forward and Backward-When this button is selected yo u can rotate an object forward or backward by clicking and dragging the object.

1i.I Tumble-When

an

this bunon is selected you can tumble an object by clicking and dragging the object. This means you can rotate the object r ight, left, forward , backward, or in any combination of these directions.

ss

~I Resize-When th is button is selected you can make an object larger or smaller by clicking and dragging the object.

Copy-When this button is selected you can make a copy of an object by clicking the object.

Ha

~I

M

uh a

m

m

ad

Figure A~ 17 The purposes of the mouse mode buttons

When this is checked you can modify an object thai is a subpart of another object.

Move up and down Move freely

Turn left and right

Tumble

I ~.mL~a~~ .. 0 ""ect SUbParts' \

Copy

'\

Resize

Turn fOlWard and backward

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1186

Appendix A Getting Started with Alice

Yo

us uf

i

Notice that juSt below the buttons a check box labeled affect subparts appears. By default, th is is not checked. When it is not checked the modifications that you make to an object using rhe mouse mode bunons are applied to the entire ob ject. However, if you check the affect subparts check box, the modifications are appl ied on ly to one of the object's subparts.

Single View and Quad View Modes

Ri

az

When Alice is in scene editor mode, you can switch the display of the world between single view mode and quad view mode. $0 far we have been usi ng single view mode, which is the default display mode. Tn single view mode you have one view of the world-the World View Window. In quad view mode you have four views of the world : the World View Window, a view fr om the top, a view from the right, and a view from the frOM. Figure A-18 shows an example of these views and points Out the quad view bunon, which you click to switch (0 qu ad view mode.

figure A -18 Quad view

m

ad

Ha

ss

an

Click here to switch to quad view. - -----,

M

uh a

m

You can use the mouse (0 modify objects in any of the views . If you look carefully at the mouse mode bunons while in quad view mode, you'll notice that the Move Up and Down bunon ~ no longer appears beca use the right and front viewing windows support up and down movement. If you want to move an object up or down while in quad view mode, you simply select the Move Objects Freely button and then move the ob ject up or down in either t he right view or the front view. You will also notice thar two new buttons appear while in quad view mode: The Scroll View bu n on and the Zoom button~. Often, when you switch to qLlad view mode the ob jects in the world will nOt be fully visible in all of the views. To remedy this you can use the Scroll View burton to scroll rhe top, right, or front view. To use the burton, fo ll ow these steps:

QJ

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

us uf

1. Se lect the Scroll View burtoo; the mouse pointe r changes into a hand tool 2 . Move the mouse poimer into the view you wish to scroll 3. Click and drag the view in the direction you wish to scroll

1187

i

Appendix A Getting Started with Alice

The Zoom burtOn allows yo u to zoom into or our of the top, right, and froor views. To use ie, foHow these steps:

az

Yo

1. Select the Zoom button; the mouse pointer changes into a zoom coo! 2. Move the mouse poiore r ioro the desired view and position it over the poim that you wIsh to zoom into or zoom our from 3. Zoom by clicking and dragging; if you want to zoom in, drag down or ro the right, if you want to zoom out, drag up or to the left

Writing Methods in Alice

ss

Figure A -19 The Method Ed itor

an

Ri

Recall that a method is a set of instructions that causes some action to take pl ace. If you want an action to take place when an Alice world is played, you have to write a method. Figure A-19 shows the location of the Method Editor in the Alice environment, where you wri te the methods that perform actions in an Alice world .

_

Ha

--_.... .... ....-.

M

uh a

m

m

ad

::~~~~~~~=======:=iiiirMethod name

Method Editor

Notice that a world.my first method tab appears at the top of the Method Editor in Figure A-19. All methods have a name, and world.my first method is the name of the method

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1188

Appendix A

Getting Started with Alice

us uf

i

that is currently open in the editor. When you create a new world Allce automaticaHy creates an empty method named world . my first method. By default, this method is automa rically execU[cd when you play the world.

Yo

In Figure A路19 notice that a group of tiles appears anhe bottom of the Method Editor. Each of these riles is an instruction that yOll can place in the method. Table A-2 describes the instructions represenred by these tiles. Table A-2 Alice instructions

You place other instructions inside a Do together instruction. The instructions that you place inside a Do together instruction are executed simultaneously. T he If/Else instruction tests a condition, which is anything that gives a true or false va lu e. If the value is tfue, then one set of instructions is executed. If the value is fal se, then a different set of instructions is executed.

together

Ri

DO

Description You place other instructions inside a Do in order instruction. T he instructions that you place inside a Do in order instruction are execU[ed in rhe order that they a ppear.

az

instru ction Do in order

an

If/Else

The Loop instruction causes one or more other insrructions ro repeat a specific number of times.

Wh ile

'f he While instruction causes one or more other instructions to repeat as long as a condition is true. The For all in order instruction steps through the items in a list, one item It a time, performing the same operation on each item.

Ha

For all in order

ss

LOOp

T he For all together insrrucrion performs the same operation on all rhe items in a list simultaneously.

Wait

The Wait instruction causes the method to pause for a specified number of second s.

ad

for all together

The print instruction displays a message in a spec ial area at the bottom of the World Running ... window. The / / tile allows yOll to insert a commenr into a method.

pr int

m

m

II

M

uh a

In Alice you place instructions in a method by dragging tiles into the Method Ed itor. For example, if you want ro place a Wait instruction in the method that you are currently writing, you SI mpl y click a nd drag the Wa i t tile into the Method Editor, as shown in Figure A-20. When you drop the tile (by releasing the mo use button) the Wait instruction wil l be crea ted in the method.

In addition to usmg the instructions that you see at the borrom of the Method Ed itor, you can also create instructi ons that execute an object's primitive methods. Once you have added an obiecr [Q a world, yOll ca n see tites fo r all of the methods that rhe object can perform by doing the following:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A

Getting Started with Alice

A~20

Dragging the Wait instruction into the M ethod Editor

Ri

az

Yo

Figure

us uf

i

1. Select the object 2. In the Details Panel select the methods tab to displa.y a set of tiles representing the object's methods

1189

-

oW

A~21

Methods displayed in the Details Panel

-----.. - _..-

ad

Ha

Figure

ss

an

For example, Figure A-21 shows an Alice world with an insta nce of the Hare class (which is in the A/limals collection ). The object, which is named hare, is selected. The methods tab is selected in the Derai ls Panel, and a set o f tiles for the hare object's primitive methods is displayed.

-I~I~~~~~~;;;;~~~~~~~::==:::::::~5i~1

m

me/hods lab.

m

Select the

M

uh a

These tiles represent the methods that the object can perform.

_.. -.... . ...,...•. _-_. ,

•••

-_.

- .-

To crea te an instruction that executes a primi tive method in the method that yOll a re currendy writing, simply drag the primitive method 's ti le and drop it into the Method Editor.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1190

Appendix A Getting Started with Ali(e

us uf

i

For example, Figure A-22 shows tile for the hare object's move method being dragged ilUO the Method Ed itor.

Yo

Most of the primitive methods require that you specify arguments. For exam ple, when yo u drop the tile for the move method into rhe Method Editor, a pop-up menu appea rs allowing you to select a direction. The allowable directions are up, down, left, right, for ward , and backward. After you select a direction, another menu appears allowing YOli to select an amount, which is the distance that the object moves. In Alice distances arc always measured In meters.

az

Figure A-23 shows an example of world.my first method after three instructions have been creatcd. When thc world contaming this method is played, the hare object will move up .] meter, then turn left 1 revolution, and then move down 1 meter. Figure A-22 Dragging t he hare . move method tile into the Method Editor

Ha

ss

an

Ri

-----,..

ad

-_.

m

...o _ _

~

l1li0 ...... -

uh a

m

Figure A-23 Three instruction tiles

M

First, the hare moves up 1 meter.

o world .my first meth od L_~"-,,,,," w orld.my f irst method Nopa'8meler/j NO \/ljT18ble3 -

)'

~i

hare -

Second, the hare turns !eft 1 revolution . ---t~ {j hare Third , the hare moves down 1 meter. ---j<~ ;i hare -

---

mow up -

l twn left -

1 meIer

moreâ&#x20AC;˘.

1 revolu~on -

move down "

1 meter -

mCJ(e._ -

more...

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Appendix A Getting Started with Alice

us uf

i

Copying and Deleting Instructions

Yo

To make a copy of an instruction tile within the same method, yOll right-click the tile and then select make copy from the menu that appears. To copy an instruction so tha t you can paste it into a different method, you drag the instruction to the clipboard. Then you open the method that you want to paste the instr uction into, and click and drag the clipboard icon to the location where you want (0 paste the instruction. To delete an instruction tile that you have created in the Method Editor, YO ll drag the tile to the rrashean.

Creating Methods

az

When you first create an Alice world, a method named wor l d . my first method is au(Omatically created in the world object. You are not limited (0 this one metbod in the world, bowever. Follow these steps to create a new method in the world:

ss

an

Ri

1. Select the world in the Object Tree. 2. In the Detai ls Panel, under the methods cab, dick the create 17CW method bunon, as shown in Figure A-24. 3. A dialog box will appear asking for the new method's name. Enrer a name in the d ialog box and cl ick the OK button . A tile for the new met hod will appear in the Details Panel, above the create new method bunon. For example, the Details Panel in Figurr.:: A-25 shows three world-level methods. 4. Create the instructions for the method in tbe Method Editor.

Ha

Figure A-24 The creale new method button

w orkfs dlltlJlls

properties fmethods rftJnCflons

t lT8lflfSt method

I

Ied ~ I

--1G'~'~.,,~.~"~.~.~m~oth~""~1I

m

ad

Click here to create a new method.

M

uh a

m

Figure A-2S An example of a world w ith three world-level methods

World -level methods

world's details propomo.

/ -------.

1191

I'>.

rmethods rfUnca6n. I

Iedit I ;:: startOfAnimation Iedit I =::malnsequence Ie cllt I

.I myfirst method

I~reate new methoda

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1192

Appendix A Getting Started with Alice

us uf

i

Once you have created the new method, you can call it from other methods by dragging the new method's tile from the Deta ils Panel into the Method "Editor and dropping it at the point where you wish to call the method.

Yo

You can also create your own CuStom methods in the ObjCClS that you place in your world. In Alice the methods that are part of an object are referred to as class-level methods. If an object doesn't provide all of the methods that you need, yo u can easily add your own methods for that objecr. You write custom class-level methods in Alice by following these steps:

Ri

az

1. Create the desired object. 2. Select the object. 3. In the Deta ils Panel, under the methods tab, click the create new method button. 4. A dialog box will appear asking for the new method 's name. Enter a name in the dIalog box and click the OK button. A tile for the new method will appear in the Details Panel, above the create new method button. 5. Create the instructions for the method in the Method Editor.

Renaming Methods

an

Once yo u have crcated the new method, yo u can caU it from other methods in the usual way: by dragging the new method's tile into the Method Editor and dropping it at the point where you wish to ca II the method.

Ha

ss

To rename a method, you simply righ t-click the method's tile and select Rename from the menu that appears. After you do rhis, you will be able to edit the name that appears on the method 's tile directly.

Creating Variables and Parameters

ad

A variable is a storage location that is represenred by a name. l.ike traditional programming languages, Alice allows you to use variables to store data. The foll owi ng variable categories

are available in Alice;

M

uh a

m

m

• Local Variables-A local variable belongs to a specific method and ca n be used only in the instructions in that method . When a method srops executing, its local variabl es cease ro exist in memory. • Worl d-Level Va riables- A world-level variable belongs to the world object, and exists as long as the world is pla ying . • Class-Level Variables- A class-level variable belongs to a specifi c object, and exists as long as the object exists. Class-level variables are like properties. • Parameter Variables-A parameter variable is used ro hold an argument that is passed to a method when the method is called. Once you create a parameter variable in a method, you must provide an argument for that parameter whenever yOll call the method.

Before you can use a variable, yo u have to crea te it. To create a local variable or a pa rameter va riable in a method, you open the method in (he Method Editor and then you click

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Appendi,.:, A Getting Sta.rted with Alice

us uf

i

the create new variable bunon or the create new parameter button. Figure A-26 shows the locations of these bunons.

1193

Figure A-26 The create new variable b utton

Yo

Click here to create a new parameter variable. -

o world.my first method L,,-:-~_ __- -- -r=====""'ii

Icreate new parameter I r--create I r---

world.my first method NoparametertJ No variable.:;

new variable

az

[Do Nothing

Ri

Click here to create a new local variable. -

ss

an

When you click either of these bunoos, a d ialog box appea rs requiring you to enter more informa tion about the variable. In the d ialog box you emer the variable's name and select the variable's type and initial val ue. Figure A-2? shows the Create New Local Variable dialog box, which appears when you click the create /lew variable button. When you click the create new parameter button, a dialog box that is virtually idemical to the one in Fi gure A-2? is displayed.

Ha

Aftcr you provide a name fo r the variable, select its type, specify its inirial va lue, and click the OK bunon, a tile fo r the variable is created in the meth od.

Figure A路27 The (reate New Locol Variable dialog box

l8J

Iii C;;;ate New Local Variable

name - ..........., cl_ _ _ _ _ _ _ _ _--"

ad

The variable's

T~:

O Ooo!ean Q Obj<ct

o othef'H I S~"~''''''-__-l- '

m

m

The variable's type -

@ NumOer

uh a

The variable's initial value -~+ Value:

O makea JUd

0

1c~"

... 1

1

M

To create a world-level variable you perform the following ste ps:

1. Select the world objcct in the Object Tree. 2. In the Details Panel select the properties tab.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1194

Appendix A

Getting Started with Alice

Yo

us uf

i

3 . Click the crea te new variable bunon, which appears at rhe rap of rhe properties tab, as shown in Figure A-2S. 4. Enter the va riable's name, type, and initial va lue in the create new variable di alog box, which is sim ilar to rhe one shown in Figure A-27. When you click the dialog box's OK button, a tile for the variable will be created in rhe Derails Panel, under the properties tab.

Figure A-28 Creatin g a world-level variable

I1lq-

Select the world object.

: ~carnera

~~~IiOht

'.'

.

az

: :lGoround

Ri

world's dll'lails

projlenles methods [ tuncllons new variable

I

Click here to c reate a new world -level variable.

I;':atlnosPhereCOlor "' ~

ss

:::~mtllentLlUhtCo'or "' . .

an

Icreale

To create a class-level variable in an object you perform the fo llowing steps :

Ha

1. Se lect the object in the Object Tree.

2. In the Derails Panel seleer the properties tab. 3. Click the create /lew variable button, whic h appears at the top o f the properties tab, as shown in Figure A-29 .

4. Enter the va riable's name, type, and initial va lue in Ih e create new variable dialog box,

m

ad

w hich is sim il ar to the one shown in Figure A-27. When you click the dialog box's OK buttOn, a tile fo r the variable will be created in the Details Panel, under the properties tab .

uh a

m

Figure A-29 Creating a cla ss~!evel varia ble

M

Select the object.

Click. here to create a

crellte new v<lrtllble

new class-level variable.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Appendix A Getting Started wi th Alice

us uf

i

Variable Assignment

1195

When you create a var iable, yO u give it an initial value. T he initial value will remain in the va riable until yOll store a di fferent value in the variable. In an Alice method you can create set instructions that store different va lues in the variable. A set instruction simply "sets" a variable to a new value.

Yo

To create a set instruction for a variable, you drag the variable rile and drop it inro the Method Editor at the point where you want the set instruction to occur. A menu appears, and you select set value. Another menu appears that allows you to speCify the val ue you wish to store in the variable. As a result, a set instruction is created .

az

Events

Table

A~3

Events that Al ice can detect

an

Ri

An evem is an actio n that takes place while a pl'Ogram is running. When Alice worlds are running, they a re capable of detecting several different types of events. For example, an event occurs when the user clicks an o bject with the mouse . An event also occurs when the user types a key o n the keyboa rd. Table A -3 describes all of the eventS [hat an Alice world can detect whil e it is running.

Description

When the world starts

This event occurs immediately when the world is started. It happens only once, each time the world is played. When the user types a key on the keyboard, this even t occurs when rhe key is released .

Ha

When a key is typed

ss

Event

m

ad

When the mouse is clicked on something This event occurs when the user clicks an object in the world with the mouse. Wh ile something is true When a condition that yO lI have specified becomes rr ue, this event occurs as lo ng as the cond ition rema ill S rrue. T his event occurs when a variable's va lue changes.

Let the mouse move <objects>

Th is event allows the user to move an object in the worl d by clicking and d ragging it with the mouse.

m

When a variable changes

uh a

Le t the arrow keys move <subject>

T his event allows the user to move an object in the world by typing the arrow keys on the keyboard. This event allows the user to move the camera throu gh the world by clicking and dragging the mouse.

Le t the mouse orie nt the camera

T his event aJlows the user to change the camera's orientation (the direction in which it is pointing) by clicking an d dragging the mouse.

M

Let the mouse move the camera

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1196

Appendix A

Getting Sta rted with Alice

us uf

i

When any of the events listed in T3ble A-3 occu r, your Alice world can perform an action in response to th at even t, such as calli ng a method.

At the top right of the screen in the Alice env ironment, you see an area labeled Events, as shown in Figure A·30. Th is area is called the Events Editor. When you create an Al ice wo rl d, a tile appears In the Events Ed itor that reads as follo ws:

Yo

When the wor l d starts, do world . my first method

az

This tile specifies that when the world sta rts, the method world . my first method will be executed. T he left portion ofrhe tile shows rhe name of an event, When the world starts, and the right portion of the tile is a drop-down box thar shows rhe name of rhe method that will be executed when the even t occurs. You can click the down arrow on rhe drop·down box to select a different method. Any method th at is selected in this tile will be automaticaJJy execu ted when the world starts.

Ri

Figure A - JO The Events Editor Click here to create ___,

a new event.

This specifies the method tha t will execute when the world starts.

Ha

ss

an

I~~~~~:::::J~~~~~~~~-~~~·~·~-~-~~~~~~~~

m

ad

The process of responding ro an event is commonly called handling the even£. In order for an Alice world to handle an event, a tile for that event mUSt appear in the Events Edi tor. When a world is first created, the only cile thac appears in the Events Ed itor is for the Whe n the wor l d starts event. If you want the world to handle any other events, you must create a new tile fOI" the event in the Eve nts Editor. To create a new event tile, yO Lt click the create new even t bunon, as shown in Figu re A-30 . A men u of ava ila ble events wi ll appear nex t. You select th e event that you want ro handle from this menu . A tile for the event will then be created in the Events Editor.

uh a

m

Most evenr riles require tha t yOu specify additional arguments, such as the method that you want ro execute in response to the event. A method thar is executed in response to an event is commonly referred to as an event handlcr. For example, rhe event rile that is shown in Figure A-30 specifies that when the world starts, world.my first method is called. The method world . my first method is the event handler.

M

Figure A-31 shows another exa mp le of an event tile. Assume that this tile appears in a world that has an objecr named fridge (a refrigerator object). The event tile speci fies that when the mouse is clicked on the f ridge object's f ridgeDoor subp art, the fridgeDoor will turn left 0.25 revolutions.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Appendix A Getting Started with Alice

do

mfrldgeJrldgeOOOr " Iturn

len "

I.

0.25 revolutions "

ImorSM. " J~

M

uh a

m

m

ad

Ha

ss

an

Ri

az

Yo

~:~

fridge.fridgsDoor "

us uf

~~ When ~. is clicked on

i

Figure A-31 Examp le of an event til e

1197

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M uh am

m

ad

Ha

ss

an

Ri

az

Yo

us

uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

o

13 14

15 16 17 18

3

4 5 6 7 8

4 5 6 7 10

9

11 12

HZTAB NEWLN

13

VTAB

14

FF

•b e d e f 10

20

"

14

21 22

15 16

23 24

18

17

,. 19

1b 1e 1d 1e 1f 7f

30 31

M

127

CR SO

51

"30

DLE DC' DC2 DC3 DC4 NAK 5YN ETB CAN

31

EM

21

"23 24 25

uh a

27 28 29

20

27

n

m

26

17

11 12 13

25

15 16

33 34 35 36 37

177

SUB ESC FS GS RS US DEL

an

32 33 34 35 36 37 38 39 40

Ri

3

SOTT STX ETY EOT ENQ ACK BELL BKSPC

NULL

ss

11 12

0 1 2

Hex

D"

Ha

9

10

0 1 2

ad

0 1 2 3 4 5 6 7 8

Printable ASCll Characters

Nonprintable ASCU Characters Name of Character H ex 0"

m

D"

az

o

Oct

Character (S pace)

20

40

21

41

"

42

23 24 25 26

43

#

44

$

45 46

% &

27

47

28

50 51 52 53

41

29

42

2. 2b 2e 2d 2e 2£ 30 31 32 33

S5 56 57 60 61 62 63

52

34

64

53

35 36 37 38

65 66 67 70

43 44

45

46 47 48 49

50 51 54

55 56 57 58 59 60

3'3.

64

3b 3e 3d 3e 3f 40

65 66 67

42 43

61 62

63

41

,

54

71 72

• I 0

,

2 3 4 5 6 7

8 9

73

"76 75

77 100 101 102 103

<

• >

? @

A

B C

1199

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

7S

76 77

49 4a 4b 4c

4d

7B

4e

79 80 81

4f

50 51

B2

52

B3

53

B4 B5 B7

54 55 56 57

BB

5B

89

59 5a 5b

90 91 92 93 94 95 96 97

98 99 100 101 102 103

104

136 137 140 141

Sf

'0 61

62 63

142 143

64 65

144 145 146 147 150 151 152

66 67

'B 69

'a 'b

'c

6d

6e

6f 70 71

o p Q R S T

\

,I

,

b

12B 129 130

13 1 132

133 134 135 136 137 13B 1 39

c

,d

142

r

h I

141 143

144 1<5 146 147 148

174

7d

175 176

7e

BO 81

200 201

82 83 84 85 86

202 203 204 205 206

87 88 89 8a

207 210 211 212 213 214 215

8b Be Bd

8e 8f 90 91 92

us uf

216 217 220 221 222

223

152 153 154 155

99 9a 9b

231 232 233

k

154

I

149

155

m

156 157 1'0 1'1

n

150 151

p q

,"

w

x y

,

173

7c

93 94 95 96 97 9B

153

o

7b

,

,

Exreoded ASCli Characters Hex Oct Character

140

g

7a

126

U V W X

Z [

79

224

225 226 227 230

M

uh a

105 10' 107 lOB 109 110 111 112 113

N

Y

78

120 121 122 123 124 125

M

132

5d 5e

llB

J

133 134 135

5c

119

K L

131

m

B'

H I

162 1 63 164 165 166 167 170 171 172

Yo

4B

72 73 74 75 76 77

az

72 73 74

114 115 11' 117

Ri

46 47

E F G

an

70 71

D

104 105 10' 107 110 111 112 113 114 115 116 117 120 121 122 123 124 125 1 26 127 130

ss

69

"<5

Printable ASCIJ Characters Hex OCt Character

Dec

Ha

'B

Printable ASCII Characters Hex Oct Character

ad

Dec

i

Appendix B: The ASCII Character Set

m

1200

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

;

,

,, ,, C

, ; 1

1

A

A t

'"

IE

"" " G

G

6 o ,


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

m

m

206 207 208 209 210 2ll 212 213 214 215 216 217 218 219 220 221 222 223 22' 225 226 227 228 229 230 231 232 233

ce ef dO d1 d2 d3 d' d5 d' d7 d8 d9 da db de dd de df eO el e2 e3 e' e5 e6 e7 e8 e9 ea eb ee ed ee ef fO f1 f2 f3

316 317 320 321 322 323 324 325 326 327 330 331 332 333 334 335 336 337 340 341 342 343 3" 345 3 46 347 350 35 1 352 353 35' 355 356 357 360 36 1 362 363 364 365 366 367 370 371 372 373 374 375 376 377

G

f ;

,6 n

" 0

i ©

N

" 00

, 5

Y

"a

l:

n IT

J

a

0

n

'"a , ~

f • a "

A A

6

2" 235

236 237 238 239 240 241 242 243 24' 245 246 247 246 249 250 251 252 253 254 255

Yo

£ U

f4

f5 f6 f7 fS f9

fa fb fe fd fe if

M

uh a

0"

az

234 235 236 237 240 241 242 243 244 245 246 247 250 251 252 253 254 255 256 257 260 261 262 263 264 265 266 267 270 271 272 273 27' 275 276 277 300 301 302 303 30' 305 306 307 3 10 3ll 312 313 314 315

H,x

Ri

9c 9d ge 9f aO a1 a2 .3 a4 as a6 a7 a8 a9 aa ab ac ad ae af bO bl b2 b3 b4 b5 b6 b7 b6 b9 ba bb be bd be bf cO el e2 e3 e' e5 e6 e7 eS e9 ea eb ee cd

Doc

an

156 157 158 159 160 161 162 163 164 165 166 16 7 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 165 186 1 87 188 189 190 191 192 193 1 9' 195 196 197 196 199 200 201 202 203 204 205

Character

ss

0"

Ha

Hex

ad

Doc

us uf

Extended ASCII Characters

Extended ASCrr Characters

1201

i

Appendix B: The ASCII Character Set

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Character

CE re

" "

+

0

i

Y

I

fi

"t %0

A £ A E E j

! I

I 6 6

•0 0 0 0

• !


M

uh a

m m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Yo

o o

az

o

Ri

The operators are shown in order of precedence, from highest to lowest.

Associatjvity

Operator

unary: left to fight

binary: right to left

[)

++

-> +

-! -

an

()

(type ) • & sizeof

ss

• I • + »

Ha

«

< <= > >=

,

right to left

left ro right left ro right left to right

left to right left to right

ad

left to right

left

[eft to

uh a

*. /-

%- &= ~

1-

«- »-

right

right

to

left

fight

to

left

left ro right

M

--

right

left to right

?:

- +-

to

left to right

m

m

II

left to right

1203

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh am

m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Symbols

\t , 37

- (negation opcralOr), 61, 93- 94 - (subtraction operator), 62, 93-94 --, 249-254

" , see Appendix

- =, 1 IJ-11 5

Student CD 1,199,202- 203,205- 206 } , 32 - (birwise negation), see Appendix J on the Student CD (destructor),774 +, 62, 64,93-94

uh a

m

m

. (dOl operatOr), 614, 739

\b, 37

M

\ n, 36

\r, 37

« (bitwise left sh ift), see Appendix J on the Student CD «(stream insertion ), 33, 144 <=, 164-166 - .40-4 1,59,175-176 ..... 164- 166, 175- 176 > , 164-1 66

ad

93-95 * (pointer variable decla radon) , 512 * = , 113-1 15

249- 254

+.. ,113- 115 < , 164-166 <> , 32

Ha

(add ress operator), 507-509 & (bitwise AND ), see Append ix J on the Student C D & (reference variables), 357 && , 199-200,205-206 ( ) , 32 * (indirection operator), 513 * (multiplication opera lOr), 62, 64,

ss

H,

&

\ ", 37 \a, 37

an

199,204-205 164-1 66 8, 32 " 62-63,93-94 %=, 11 3-1 15 !=,

\\,37 \', 37

I , see Appendix J on the J

!,

/ , 62,93-94 /* - /,68-69 //, 29,32,68-69 / =,1 13-115 ;:, 740 i, 14,32 ? :, 218-221

{, 31

CD

actual parameters, 319 addition opennor (+), 62, 64,

Ri

- > (object po inter), 748 - > (struCt ure poi mer), 636

J on the Studem

>=,164-1 66

»(bitwisc right shih), see Appendix J on the SruJ em CD »(stream ex traction), 84- 85, 145

A abs libra ry function , 131 abstract array data type case study,

795- 799 abstract base classes, 942-946 abstract data type (ADT), 609-611 in [h~ STL, 1007 access specifiers, 736- 737 bllseciass, 900- 901 accessors, 740-741 accumulator, 280-281 actual arguments, 319

93-94

address, 4, 15,507 address opera[Qr ( &), 507-509 ADT, see abstract data type aggregation, 872-877 has-a relationship, 875 UML, depicted in, 877 algebraic expressions, 95 algorithm, 7

STL, 1008-1 010, 1014-1 020 Alice software, 11 7 1-11 97 adding objects, '1 176- t ! 79 camera controls, 1 179 creating methods, 1191-1192 creating va riables/parameters, 1192-1194 creating world, 11 76 deleting objects, 1184 downloading/installing, 1171 environment, J 173-1174 eventS, 1195- 1197 insrructions, copying/deleting, 1191 modifying objects, ill Scene Editor mode, 11 84- 1186 playing world, 1175 primitive methods, 1181-1184 properties, 11 80-118 1 renaming of methods, 1192 selecting objects, 1180 single vicw/q uad yic w rno<.les, 1186-1 187 variable assignment, 1195 Welcome to Alice! dialog box, 1]71- 1173 writing methods, 118 7- 1190 ALU,3

1205

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1206

205-106 anonymous fnum, 648 anonymous unions, 641-645 append membcT function, string class, 596 application software, 5-6 argument, 95-96, 319 command~line. see AppendIx H on the Student CD default, 353-356

arithmetic expressions. 91-97 ari t hmetic logic unit lALU), 3 arithmetic operators, 6 1--64 arrays

205-206, 1203

accessing elements, 389-396 assigning one to another, 406-407 averaging values in, 408 binary search, 470-473 bounds checki ng, 396-398

string class, 596 vector, 450, 1013 atof library function, 577-578 atoi library funnion, 577-578 atol li bra ry function, 577-578 attributes, 730

an

bubble SOrt, 481-484 char, 88-89

at member (ul'lction

defining, 88, 387-388

908-909 multiple, 949-954 pointers. 935-938 BASIC, 9 begin member function iterat or, 1013 string class, 596 vector, 1013 binary digit (bit), 4, see also Appendix J on the Srudent CD binary files, 696-70t binary num bers, 7, see (Ilso Appendix J on the Student CI) binary operator, 61 binary search, 470-473 , 1125-1127 efficiency, 473 recursive verSion, 1125-1127 binary trees, 1145-1165 applications of, 114 7 child nodes, 1145 creating, 1149-1150 deletinga node, 1156-1164 morder traversa l, 1152-1155 inserting a node, 1150-1152

M

uh am

m

ad

duplicating, 541-543 element, 388 as {unction arguments, 415-424, 430-431 highest and lowest val ues, 409 implicit siz.ing, 402 initialization, 399-404, 429 initialization, partial, 40 1-402 inputting and outputting, 391-396 linear search, 467-470 loops, using with, 392 memory addre5~, 406 memory requirements, 388-389 of objects, 784-786 off-by-one error, 398 parallc:l,412-414 partia lly filled, 409-411 passing to functions, 415-424 and pointers. 516-520 priming coments of, 407-408 reading from a file imo, 394-395 selÂŤdon SOrt, 485-488 SIU declarator, 388, 390 strings, 433-435, 568-569 strings, initializing with, 403-404 of structures, 623-626 subscript, 389- 390 summmg values in, '108, 431-433 three or more di men~ions, 435-436

B back member function , list, 1059 bad member funcuon, file stream, 685 bad alloc exceplion, 989-990 basecase, recursion, 1112 base class, 896 abstract, 942-946 access speci~cat i on, 900-901,

ss

1027-1028 comparing, 411-412

Ha

compared co li nked list,

leaf nodes, 1145 nu ll address, 1145 opcmions, 1148-1165 postorder traversal, 1152-1155 preorder traversal, 1152-1 155 rOOt node, 1145 search trees, 1147 searching (or a value in, 1152-1155 subtrees, 1146 template considerations, 1165 traversing, 1152- 11 55 tree: pointer, 1145 binary search algorithm (STL), 1008,1014-1016 binding, 929 dynamic, 929 static, 929 blt,4 working with, see Appendix Jon the Srudcnt CD bitwise operators, see AppendixJ on the St"dent CD block scope, 209 blueprinrs, classes as, 733-734 bool,57,176-177 rewrning from a funerion, 340-342 Boote, George, 57 Boolean expression, 57,164 bounds checking, arrays, 396-398 brace, 3 1-32 break Statement, 224, 290-292 bubble sort, 481-484 buffer, keyboard, 87 buffer overrun, 126 byte, 4

us uf

the Student CD

logi c~J opera cor, 199-201,

two-dimensional,426-433 using an enum with, 649-650 writing Contents to a fi le, 395-396 arrow operator (-Âť, 636, 748 ascending order, 481 ASCII,49. 1 199-1201 assign member function, sHing class, 596 assignment combined, 11 2-,115 membcrwise, 838-839 multiple, 112- 1J 3 operator (-), 59 statemem, 40-41, 59 associative containers, 439, 1007- 1008 associativity, 94, 164,

Yo

J on "

see Appendix

az

& bitwise opera tor,

Ri

AND

i

Index

(

C#,9 C programming language, 8-9 C-strings, 51 - 53. 88, see also string appending one to another, 570, 572-573 ar rays, 433-435 char array for holding, 88-89 compari ng wirh Strcmp, 2 13-217 concatenation, 570, 572-573 copying, 57 1-573 functions to handle, writing, 582-587 internal SfQcage of, 566-569 leng(h, getting, 569-570 library functions to work with,

569-576 nul! terminalOr, 51, 88, 566-567 numeric conversion functions. 577-582 searching within, 573-575 sorting, 217

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

120

M

uh a

m

m

us uf

public members, 736-737 responsibilities, identifying, 808 scope resolution operator ( : : ),

740

Yo

separaTing specification from implementalion, 753-759 setter fu nction, 740 specification file, 753 stale da ta, avoiding, 748 static member functions, 830-833 static member variables,

826-830

lemplates, 997-1006 this pointer, 848 UM L, 799-802 virtua l functions, 929-935 whole-part reialiol\silip, 875 clear member function file stream objc<:ts, 685 string class, 596 vector, 447-448, 450, 1014 close member function, file Stream objects, 143-144 closing a file, 143-144 cmath header file, 96,131 CO BOL,9 code reuse, 308 coercion, tOl collaborations, class, 878-882 combined assignmem operatOrs, 112-115 command-line arguments, see Appendix H on the Student CD comment, 29, 68-69 / 1,68--69 /" "1,68-69 multi-line, 68-69 single line, 68-69 compact disc (CD), 5 compare member funcrion, string class, 597 compiler, 10--1 1, 674 concatenate, 570 conditional loop. 270 conditional ope~a tor, 218-221 conditionally-executed code, 169-170,177-179 console, 33, 84 console output) 33 const, 107- 109, 255, 529-531 member hmctions, n8, 741 constront j)ointers, 532-533 consta,us global,344-349 named, 107-109 pointers to, 529-531

ss

an

Ri

az

access specifiers, 736-737 acce~sors, 740-741 aggregation, 872-877 argumentS to constructors, 766-774 array of objects, 784-786 base, 896 base class access, 900-901, 908-909 as blueprint, 733-734 collaborations, 878-882 const member functions, 738,741 construclQr overloading, 778-782 conStructors, 762-774 conversion, object, 870-872 copy constructor, 839-843 declaration, 736 default constructor, 766, 773-774,782 denved,896 desrructors, 774-777, 782 dot operator (_), 741 dynamically allocated objects, 749-751 finding, 802-810 forward declaration, 835 fri end functions, 833-837 getter function, 740 "has-a" reiationship, 875 hierarchies, 921-927 implementation file, 754 include gua rd, 754-755 inheritance, 895-904 in li ne member functio ns, 759-76 1 instance, defining, 741 instance variablcs, 825-826 is-a rclationship, 896, 938-939 member functions, defi ning, 739-740 memberwise assignment, 838-839 mutators,740 objects vs., 732-734 operator overloading, 843-870 overloading member func tions,

Ha

ad

ca ll, function, 95 calling a function, 310-315 capacity member function string class, 596 vector, 450,1013 capitalization of variable names, 44 case conversion, character, 563-565 case statement, 222 case stud y abstract array data type, 795-799 Demetris Leadersh ip Center, 474--480,488--496 dollarF'ormat function, 598-599 General Crates, [37-140 Home Software Company, 598-599,788-795 National Commerce Bank, 437--439 United Cause, 545-549 cast expression, 104 casring, type, 104-106 catch block, 973 catch key word, 973 central processing unit (CPU), 3-4 c har , 49-53 char array, 88-89 character case cOl'lversion, 563-565 tolower fUl'l ction, 563 toupper funerion, 563 character literal, 50-52 character testing, 559-563 isalnum function, 560 isalpha function, 560 iSdigit function, 560 is lower function, 560 i sprint function, 560 ispunct function, 560 isspace function, 560 isupper function, 560 cin, 17.83-89 get member function, 128-131 getline member function, 127-128, 130, 568 ignore member function, 129-130 keyboard buffer, 87 reading a character, 127- 129 rrading a line of inpm, 127-128 reading multiple values, 85-86 setw manipulator with, 125- 127 strings) reading) 88-89 width member functi on, see Ap~ndix L on the Student CD circular linked list, 1058 class, 732-752 absuact, 942-946

i

Index

782

placement of public and private members, 738-739 pointers, 748-751 polymorphism, 927-941 private member func tions,

782-784 Drivare members, 736-737, 752-753 problem domain, 803 protected members, 904-907 public member funct ions,

737-738

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1208

default, 766, 773-774, 782 default arguments with, 772 overloading, 778-782 containers, 439, 1007 associative, 1007- t 008 sequence, 1007 continue sratcmenr, 292-293 comrol unit, 3

control variable, loop, 257 conversion

Ri

by casting, ]04-106 objcct, 870-872 string/numeric, 577-582 ty~. 101 copy conStructor, 839-843 defaul t, 843 copy member function,

an

string class, 597 cos library function, 131

algorithm (STLJ, 1009, 1016-1017

ss

counr-controlled loop, 270 counters, 263-265 cout, 17, 31, 33-37 fixed manipulatOr with,

121-124 left manipulatOr with,

123-124 precision member funct ion,

see Appendix L on the Student CD

ad

right manipulator with,

123- 124 setf member fu nction, see Appendix L on the Student

CD

uh a

m

m

setprecision manipulator with, 119-121, 124 setw manipulator wirh, 117- 11 S, 124 showpoint manipulator with, 123-124 unsetf m!::mber function, see Appendix L on the Studen t CD width member function, see Appendix L on the Student

CD

CPU, 3-4 CRC cards, 881-882

M

Ha

count

cstdlib header file, \33,367,577 cstring header file, 214, 569 cti.me header file, 133

pop_front member function, 1097 push back member function, i'097 dequelle operation, 1085-l 088 dereferencing pointers, 513 derived class, 896 descending order, 481 designing a program, 17-21 desk-checking, 20 destructors, 774-777, 782 base and derived classes, in, 910-915 virrual,939-941 digits displayed after decimal point, 119-123 direct recursion, 1118 directive, preproceuor, 3D, 38 disk drive,S divide and conquer, 307-308 division integer, 62,10 1-102 operator (I), 62, 93- 94 remainder of, 62-63 by zero, 182, 971-972 do -~hile loop, 265- 269,287 with menus, 267-269 pOSHeSt, 265-266 dollarFormat function Case study, 598-599 dot operator ( _),614,741 double, 54-57 double precision, 54-55 do ubly linked list, 1058 drivers and stubs, 369-371 dynamic binding, 929 dynamic memory allocation, 534-538 bad alloe exception, 989-990 objecrs, 749-751, 766 , 777 structures, 638-639 dynamic queues, 1085, 1093-1096 dynamic stacks, 1068, 1078-1082

us uf

910-915 copy, 839-843

D data hiding, 730-731 data type, 44-46 abstract, 609-611 bool,57 casring, 104-106 char,49-53 coercion, 101 conversion, 101,104- 106 demotion, 10 1 double, 54-57 float, 54-57 floating-point, 54-57 generic, 991 int, 45-46 integers, 44-48 l ong, 45-46 long double, 54-56 numeric, 44-45 primitive, 6\0 promotion, 101 ranking, 100-101 short, 45-46 size of, derermining, 58 unsigned int, 45-46 unsigned l ong, 45-46 unsigned short, 45-46 database ma nagement systems, 673 debugging desk路checking,20 ha nd- tracing, 135-136 stubs and drivers, 369-371 decimal point, digits displayed after, 119-123 decision structure, 168 dectar:aion,16 decode, 4 decrement operator (- - ), 249-254 mathematical expressions, in, 253 postfix mode, 250-253 prefix mode, 250-253 relational expressions, in,

Yo

arguments passed to, 766-774 base and derived classes, in,

az

conscructQf, 762-774

i

Index

253-254 default arguments, 353-356, 772 conSUUClOr, 766, 773-774, 782 copy construclOr, 843 defaul t Statement, 223 Ide fine directive, 109-111,755 definition, variable, 16,39-40, 209-21 1 d elete operatOr, 536 Demelris Leadership Center case study, 474-480, 488-496 demotion, type, 101 depth of recursion, 1109 deque (STL ty pe), 1007, 1097-1098 front member function, 1097

E

E notation, 54- 55 EBCDIC, 49 editor, text, 10-U element, 388 working with, 389-396 clements, language, 12-16 else, 182 trailing, 192, 194- 195 empty member function list, 1059 stack,1083 string class, 597 vector, 448-450, 1014 encapsulation, 130, 730

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1209

989- 990

fil~,

execU[c,4 exhaustive algorithms, 1136-1138 exit code, 367 e xi t library function, 366-367 EXIT_FAILURE constan t, 367 EXIT SUCCESS const3nt, 367 exp library funct ion, 131 exponents, 95 expression, 91 algebraic, 95 arithmetic, 9 1-97

an

653-654

Boolean, 57. 164 cast. 104

ad

erase member function list, 1059 string class, 597 vector, 1014 error logical,20

Ha

685

ss

stepping through an array widl, 649-650 enumera ted data types, 645---655, see also enum enumeratocs, 646 eof member function, file stream,

eQua l-to ooerator ("':: ). 164-166

initialization, for loop, 270-271, 275,276-277 mathemadcal,91-97 relational, 164 test, for loop, 270-271 update, for loop, 270-271, 275, 276-277

recQvering from, 982- 984

m

syntax, 10 error teslmg. files, 685- 687 escape sequcncc, 36 \\ , 37

M

uh am

\', 37 \ ~ , 37 \ft , 37 \b , 37 \n,36-37 \r, 37 \t, 37 newline, 36 exception, 535, 971-990 bad alloc, 989-990 catch block, 973 dynamic memory allocation, 535 extracting dara from, 984- 988 handler, 972 handling, 973-975

10-11

Ri

az

multiple, handling, 978-982 new operator, 535 not catching, 975 object-oriented handling, 975- 978 recovering from errors, 982-984 rethrowing, 988- 989 throw key word, 973 throw polm, 973 th rowing, 973 try block, 973 try/catch construct, 973- 975 un winding the Slack , 988 ~xcl u sive OR, bitwise, see Appendix J on the Student CD executable code, 10-11

i08 :: in, 675 ios : l out, 675 ios: I trunc, 675 file buffer, 143 file VO ap~nd mode, 675 binary files, 696-70 1 buffer, 143 closing a file, 143-144 end-of-file marker, 676 error tesling. 23 1, 68S--ii87 existence of a fi le, checking for, 678-679 fi le stream obiÂŤts, 141,674 f s tream header file, 141 general process, 14\ introduction, 140-148 multiple files, openi ng, 695 opening a file, 142-143 opening for both input and oU[pU[,7 14-716 output formaning, 680--683 passing stream objects [Q fu nctions, 683--684 random-access, 706-714 read position, 146 r~ading a cha racter, 692 reading a line, 689 readi ng from \I. file, 145-148 reading from a file imo an array, 394-395 reading with a loop. 284-286 records, 702-706 n:windinl5,713-714 selling a program up for, 141-142 wriring a chanlcter, 694 writing an array to a file, 395- 396 writ ing to a file, 144-145 file names, 679--681 file stream objeclS, 141 member functio ns, 688-693 passing 10 functions, 683--684 find algorilhm (STL), 1009, 10 18- 1019 find member function, st r ing class, 597 "nding Ihe dasses, 802-810 fiest-in first out (FIFO). 1085 fixed manipulator, 121-113,680 fixed point notation, 12J -122 Oag,176-177 flash m~mory, 5 float , 54-55 floating-point data types, 54- 57 comparing, 173-174 flowchart, 19, see also Appendix 0 on [he Student CD

us uf

memory allocation error,

Yo

end member function iterator, 1013 list , 1059 s tr in g dass, 597 vector, 1014 end-ol-file marker, 676 lendif dIrective, 754-755 e ndl, 35 endless loop, 258 enqueue operation, 1085-1088 enum , 645--655 anonymous, 648 assigning an imeger to an enum va riable, 647 combining declaration and definition, 655 comparing enumerators, 647 defining an enum variable, 646 enumerators, 646 math operalOCS with, 649 outpuuing valu~ with an anum , 651---652 scope and cnumerators, 654 spc<:ifying enumcralOr values,

i

Index

F

factorial algorithm, 111 2-1115 fail member function, file Stream, 231,685 fetch,4 fetch/decode/exec ute cycle, 4 Fibonacci numbers, 11 20- 11 22 field, bit, Jee Appendix J on the Siudem CD field width, 117, 125- 126 file access flags, 675 ios: : app, 675 i05 : late, 675 ios : : badbi t, 685 i os I :binary , 675 ios I :eofbit, 685 .ios I : failbit, 685 los: : goodbit, 685 ios : : hardfail, 685

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1210

270-271,275,276-277 instead of while o r do - while,

273-274 p re test, 274 test expression, 270-271 update expression, 270-271, 275,

276-277 uscr-connolled , 275-276 for_each algorithm (STL), 1009,

1019-1020

c; g ++ command, 10 Gencra l Crates case study, 137-140 generalization and specialization, 895 generic function, 990 type, 991 get member functio n cin , 128-131 file SHeams, 692 get line member function cin, 127-128,130,568 fi le streams, 689 getter function, 740 globa l variables and constants, 344-349 good mem ber function, filc stream, 685 greater·than operaTOr (», 164-166 grea ter-than or equal-tO operator (>:::),164- 166 greatest common divisor (GCD),

an

list, 1059

bool va lue, returning, 340-342

call,95,310-315,334-337 code reuse, 308

uh a

m

m

ad

declara tion , 317 defau lt arguments, 353-356, 771 definition, 309-310 fi le stream objects as arguments, 683-684 frie nd, 833-837 generic, 990 header, 309 in line, 759-761 local variables, 333, 342-344 main, 30-31 me mber, 730 modular pmgramming, 307-308 names, 309 overloading, 362-366 overriding, 939 paramerer JiSt, 309 paramcters, 3 19 passing by reference, 356-361,525 passing by value, 324-325 pointcrs as parameters, 525- 529 prOWtyp<"5, 31 7-31 R pure virtual, 942

Ha

ss

vector, 10 '14 fstream header file, 141-142 fs t ream objects, 675 funct ions, 30 arguments, 95-96, 319 body, 309

M

IDE, 11

idenrifiers, 43-44 capitalization, 44 legal,44 if/else statement, 181-183 if /e l s e i f statemcnt, 191-195 trailing else, 192, 194-195 if statement, 168- 179 conditionally·executed code, 169-170,177-179 expanding, 177- 179 noating point compa risons, 173- 174 indentation, 173 nested,184-191 programming style, 173 tHndef directive, 754-755 ifstream objects, 142,674,678 » used wi th, 145 close membe r function, 143- 144 fail member function, 23 1 ope n member functio n, 142-143 ignore member function, cin, 129- 130 implementation nle, class, 754 implicit sizing, arrays, 402 li nclude direclive, 30, 38-39, 757 include file direCTo ry, 757 includc guard, 754-755 increm~nt op~ rator (++ ), 249-254 mathematical expressions, in, 253 postfi x mode, 250-253 prefix mode, 250-253 relational expressions, in, 253-254 indentation, 69-70, 173,259 indireci recursio n, 1118 indirection operator, 5 13 infi ni te loop, 258 inhcritancc, 895-904 base class, 896 class hierarchies, 921 - 927

Ri

formal argument, 319 formaned input, 125-130 formatti ng output, 116- 124 FORTRAN,9 forward declaration, 835 friend class, 837 functions, 833-837 key word, 833 front member function deq ue , 1097

us uf

header, 270 initia liza tion expression,

cstd l ib , 133,367,577 cst r ing , 214,569 ctime , 133 £Stream , 141 - 142 iostream , 30,38- 39 prestanda rd sty le, 71 string, 588 hexadecima l literals, 48 hierarchies, class, 921-927 hierarchy chart, 19 high· level languages, 8 H oare, C.A.R., 1131 Home Software Com pany case sf",dy, 598-599,78 8-795

Yo

f o r Joop, 270-279, 2S7 arrays and, 392

az

rec ursive, 1107 redefining base class, 917-921 reference variables as parameters, 356-361 return statement, 330-331, 333 return type, 309 ret urning a structure, 633-635 returning a value from, 332-342 retu rning pointers from, 538-540 send ing data into, 319-323 signature, 363 static local va riables, 350-353 static member, 830-833 string hand ling, 582-587 structures as arguments, 630-633 stubs and dri vers, 369- 371 templates, 990-997 value-returning, 332-342 vi rtual, 929-935, 942 void, 309- 310

f mod library function, 131

i

Index

1119- 1120 H hand·tracing, 135-136 handler, exception, 972 I-bnoi, Towers of, 1128- 11 31 hard disk, 5 hardware, 2-5 CPU, 2-4 input devices, 2, 5 main memo ry, 2, 4 output devices, 2, 5 secondary storage, 2, 4-5 "has·a " relationship, 875 head, linked list, '1029 header file, 30 cltlath, 96,131

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1211

uh a

ios: : failbit status nag, 685

M

ios ; : goodbit status flag, 685 ios: : hardfail status flag, 685 ios :: in access lIag, 6 75 1.05 : : ou t access flag, 675 iostream header file. 30. 38-39 ios : : trunc access flag, 675 " is-a" relationship, 896, 938-939

us uf

'e'rano,

\3')

Yo

strcat, 570-571,575 strcmp.213-217,576 strcpy, 571-572,575 strlen, 569-570,575 strncat , 572-573,576 strncpy, 572-573,576 strstr , 573-576 tan, 131 time, 133 tolower, 563 toupper, 563 lifetime, 344 LIFO, 1067 linear sea rch, 467-470 efficiency, 470 lines and statements, 14-15 linked lisl, 1027-1029 appending a node, 1030-1036 circu la r, 1058 class as node type, 1042 compared to arrays, 1027-1028 comparcd to vector, 1027-1028 composition o f, 1028 counting nodes, 1123-1124 deleting a node, 1042-1045 desrroying the list, 1045 displaying nodes in reverse, 1124-1125 doubly-linked, 1058 head, 1028 inserting a node, 1037-104 1 nodes, 1027 null add ress, 1028 operaTions, 1029-1046 recursion with, 1122-1125 self-referential structure, 1029 singly-linked,1058 template version, t046-1057 travcrsing the list, 1036-1037 linker, 10-11 Linux,lO list (STL type), 1007, 1059-1060 back member function. 1059 empty mcmber function, 1059 end member fu nction, 1059 erase member function, 1059 front member func tion, 1059 insert member function. 1059 merge member function, 1059 pop back member function, 1 059 pop_front member function,

az

J Java, 9 JavaScript,9

K key words, '13-14, 43-44 keyboard buffer, 87 input with ci n. 83-89 l language elements, 12-16 last-in-fifS[-ollt (LIFO), 1067 l eft manipulator, 123-124 length member function, str ing class, 594-595, 597 leSS-Than operator ÂŤ), 164-166 less-tha n or equal-to operator (<-I, 164-166 li brary, runtime, 10 library function, 95 abs, 131 atof, 577-578 atoi, 577-578 atol, 577-578 cos, 131 exit , 366-367 exp, 131 fmod, 131 isa1num, 560 isalpha, 560 isdigit, 560 is lower , 560 isp.J;"int. 560 ispunct , 560 iss pace , 560 isupper, 560 itoa, 577-579 log. 131 10g10,131 mathematical,131-134

ad

m

m

(I DE), 11

ios: : app access flag, 675 ios : : ate access flag, 675 i05 : : badbi t status flag, 685 ios : : binary access flag, 675, 697 ios : : e ofbit Status flag, 685

pow, 95- 97 rand, 133-134 sin, 13J sqrt, 131

Ri

cbs"" 896

/lis_a n relationship, 896 multiple, 949-954 redefining functions, 917-921 and templates, 1003-1006 initialization, 60 arrays, 399-404, 429 arrays of objects, 785 list, 399 partial, array, 401-402 pointers, 522 structu re, 619-622 StruCTU re array, 626 vanable,60 initialization expression (for loop), 270-271,275,276-277 in line expansion, 761 member fu nctions, 759-76 1 inorder traversal, binary trees, 11 52-1 155 input, 16-17 with cin, 83-89 devices,S formaued,125-1 30 validarion, 197,207-208, 261-263 input-output Stream library, 38 insert mem ber function string class, 597 vector, 1014 insert mcmber fu nction lis t, 1059 instance, 613 class, 741 variables, 825-826 instantiation, 74 1 int,45-46 integer data Iypes, 44-45 division, 62, 101-102 IntegerList class, 795-799 integrated development environment

an

dCT;VC~\

isa1num library function, 560 isalpha library function, 560 i.sdi.9it library function, 560 is lower library function, 560 ispr int library function, 560 ispunct library function, 560 isspace library function, 560 isupper library funCTion, 560 iteration, loop, 256 iterators, 1007-1008 [ 1 operator, 1010-1013 begin member function, 1013 bid irectional, 1008 end member function, 1013 forward, 1008 input, 1008 output, 1008 random-access, 1008 i t oa library function, 577-579

ss

910-915

Ha

conStruCtors and desuuctots,

i

Index

1059 push back member function, i059

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1212

az

literal,41-42 character, 50-52 double, 55-56 float . 55-56 noating-point,55 hexadecimal,48 integer, 47-48 long lmeger, 47-48 octal, 48 suing, 31, 41-42, 5 I, 566 loca l scope, 209 local variables, 333. 342-344 stat ic, 350-353 log library funellon. 131 log 1 0 library function, 131

205-206 precedence, 205-206 ~ h orH;:ircui l eval uation. 200, 202 long, 45-46

long double, 54-55 loops, 254

bit, 4 byte, ..

flash,S main,4 random-access, 4, 15 memory allocation, dynamic, 534-538 menus, 195-197,227-229,267-269, 326-328 merge member function, list, 1059 message, 22 methods, 73 1 Microsoft Visual C++ 2008 express Edition, see Appendix M on the Studem CD min_element algorithm (ST!.),

M

uh am

m

ad

accumulator variable, 28D-281 arrays and, 392 breaking out of, 290- 292 conditional,270 condit Ionall y-executed body, 255 contin ue Sl:uement, 292- 293 com rol variable, 2S7 count-comrolled,270 counters, 263-265 counting iterations, 263-265 deciding which to use, 287 do- while, 265-269,187 for. 270-279,287 indemation, 259 inhn ilc, 258 iu:ration, 256 neSltd,287-290 po!incst, 265-266 pretest, 257, 274 programming style, 259 readmg a file with, 284-286 running total, 280- 28 t sentinels, 283-284 user-controlled, 267, 275-276 .... hil e , 254-263,287 low-level language5 ,8 lowercase conversion, character, Ivalue,59

poi mer,536

statement, 172 termmatOr, 5 1, 88, 566-567 numeriC data, 44-45

Ri

a~sociativlty,

an

" lAND), 199-201,205-206 II (OR), 199,202-203,205-206

ss

logical oper:IlOrs, 199- 206 ! (NOT), 199,204-205

Ha

logical error, 20

563- 565

negation operator (- J, 61 negati ve numbers, in binary, see Appendix J on the Student CD nested i f statements, 184-191 loops, 287- 290 structures, 626-629 .N ET Framework, see Appendix G on the Student CD new operato r, 534-538 new line, priming, 35-36 node, linked list, 1027 not eq ual-to operator (! -), 164- 166 NOT (1) operato r, 199,204-205 null character, 51, 88, 566- 567

us uf

reverse member function, 1060 size member function, 1060 swap member function, 1060 unique member funclion, 1060

M machine language, 7 main function, 30-31 main memory, 4 managed C++, see Appendix G on the Studem CD manipula wr, stream, 35 mantissa, 54-55 map {STL type}, 1008 mathematical expressions, 91-97 malhematical library functions, 131-134 max element algorithm (STL), 1009, 101 7-10 18 member function s, 130-131, 730 binding, 929 dynamic binding, 929 overriding, 939 (edefining, 917- 921, 939 static, 830-833 static binding, 929 this palmer, 848 virrual,929-935 memberwise assignment, 838-839 memory address, 4 , 15,507

Yo

list (STL type) (continued) push_front membrr function. 1059

i

Index

1009,1017-1018 modular programming, 307-308 modulus operator (\), 62-63, 93-94 multimap {STl type), 1008 multiple assignment, 11 2-1 13 multiple inheritance, 949- 954 multiplication operator ( 路 ),62,64,

93-95 multiset (STL type), 1008 mulritasking,6 multiuser operating system, 6 nlUiatOrS, 740 N named COnStantS, 107-109 namespaccs, 30, see also Appendix F

on the Srudent CD

National Commerce Bank case swdy, 43 7-439

o

objcct, 730 aggrega tion, 872-877 array of, 784- 786 attributes, 730 class vs., 732-734 code, Woo l 1 conversion, 870--872 data hiding, 730-73 1 dynamically allocated, 749-751, 766, 777 encapsulation, 730 file, 10-11 methods, 73 1 pOinters, 743-75 1 reusability, 732 state, 745 obiect-oriented design aggregation, 872- 877 class collaborations, 878-882 classes, find ing, 802-810 CRCcards,88 1-882 generalization and specializ.1tion,

895 inheri tance, 895-904 problem domain, 803 responsibilities, identlrying, 808 UML, 799-802, 877 object-orienred programming (00 1'), 21-22,131,729-735 octal litera ls, 48 off-by-one error, 398 ofs tre am objects, 142 ,674,678 芦 used with, 144 c l ose member funct ion, 143-144 fail m~lllber funerion, 23 1 open member {unction, 142- 143 OOP, 21 - 22, 131,729-735

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1213

858- 860 OR A

-", JJ3-1l5

" "' , 113-115

. (dOT operatOr), 614, 741 / , 62,93- 94 /'='. 113-115 1, (conditional), 218-221

I I, 199,202- 203,205-206 +. 62,64,93-94 ·H, 249-254 +- ,113-115 <, 164-166 «,33

bmary,61

m

uh am

bitwise, see Appendix J on Ihe Student CD combined assignment, 112- 115 condi tional,218- 22 1 delete,536 logical, 199- 206 new, 534-538

overloading, 843-870

M

pccc.:d",ncc, 93, 205-206, rdadonal, 163-l67

1203

533 to constants, 529-531 delete operator, 536 dynam.c memo r y "lIo.;o,,;on,

534-538

scope resolution (: :),740

as function paramelers, 525-529

:liz;eo.f , .58

;ndircc';on operator (.), .5 13

ternary, 61 unary, 61 operator overloading, 843-870 dummy paramerer, 856

us uf

variables, 509-516 polymorphism, 927-941 abstract classes, 942- 946 base class poimers, 935-938 dynamic binding, 929 overriding, 939 pure virtual function, 942 and references or pointers, 933-935 static binding, 929 virtua l destructors, 939-941 virtual funcrions, 929- 935, 942 pop member function, stack (STL), J083 pop o peration (stacks), 1068- 1069 pop_baCk member function list , 1059 vector, 446-447,450,1 010 pop_front member function deque, 1097 list, 1059 ponabiliry,10 postfix mode, 250-253 postorder traversal, binary (rees, 1152-1155 pomest loop, 265-266 pow function, 95-97 precedence, operator, 93, 205-206, ] 203 precision, 119 pr:eciaion m~mbcr function, cout, see Appendix Lon the Student CD prefix, template, 991, 997-99S prefix modc=, 250-253 preorder traversal, binary trees, 11 52- 1155 preprocessor, 10-11 preprocessor directive, 30 prest(llldo.rd Cu, 71 prete~ t loop, 25 7, 274 primitive dafa types, 610 private member functions, 782-784 private members, class, 736-737, 752-753 problem domain, 803 procedural programming, 21-22,

Ri

ad

<- , 164-166 • ", , 40-41,175-176 ==, 164-1 66,1 75-176 >, 164-166 >.. , 164- 166 », 84-85 arithmetic, 61-64 associativity, 94, 164, 205-206 , 1203

an

!"'. 164- 166 " 62,64,93-94 , .. , 113-115 & (address), 507- 509 &&.199-201,205- 206 .. (indirection), 513 " (multiplication), 62, 64, 93-95

bitwise operator, see Appendix J on thc 5IUdent CD Illogical operator, 199, 202- 203, 205- 206 ompUl, 16- 17 output devices, 5 output formatting, 116-124 files, 680-683 overflow, 102-103 overhead, 1112 overloading, operator, 843-870 overloading functions, 362- 366 constructors, 77S- 7S2 member functions, 782 templates, 995-996 overriding, 939 overrun, buffer, 126 p para llel aro:ays, 412-4 14 parameleu, 319 pointers as, 525-529 reference vllrillbles as, 356- 361 parentheses, grouping with, 94 Pascal,9 passing by reference, 356-361, 525 passing by value, 324-325 pointers, 509 address operator ('I, 507-509 arid"l!ct; ... wit", 52()...52t and arrays, 5 16-520 base class, 935- 938 comparing, 523- 525 constant pointers, 532-533 constant pointers to constanrs,

ss

!, 199,204-205

'lI\'I~...\~t't ~\'i\\~ <;)!jKtaJ;Q~ 636

az

CD

(objecr pointer), 748

-> (slructure poinler), 636

Ha

->

bitwise exclusive, see Appendix J on Ihe Student

returning (rom [unclions, 538- 540 to structure, 636-640

Yo

general issues, 849-850 overloading .. , 844-848 overfoading I I, 864-870 oVtr'loaOlng >~ <IIIU <.<., 860-864 overloading math operators, 850-855 overloading postfix ++, 856 overloading prefix ++, 855 overloading relational operatOrs,

open mcmber function, file Stre3m objcct$, 142- 143 nneninll ~ fi le. 142- 143 operands, 59 operating systems, 5-6 multitasking, 6 multiuser, 6 single tasking, 5 single user, 6 operator, 13-14 - (negation), 61, 93-94 - (subtraction), 62, 93-94 -- , 249-254

i

Index

initializing, 522 new operatOr, 534- 538 null,536 to objects, 748-751

729-730 processing, t 6-17 programmer-defined idenlifier,

13-14 programming languages, 7-10 high-level, 8 low· level, 8 programming process, 17-21

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1214

\lrog.rammin& styk, 69-70

recursion,l107-JJ3!J base case, 1 1 12

push membe r functIon, stack (STL), 1083 push operation (stacks), 1068 pus h_back member function

d eque , 1097 list, 1059 vector. 443,450, 1010 pus h_ f ront member function, list , 1059 put member func tion, file strea ms,

infinite, 1108 versus iteration, 1138-1 tJ9 linked list operations, 1122- 1125 problem solving with, 1112-11 18 QuickSort algorithm, 1131-1135 recursivecasc:, 11 12 recursively defined problems,

11 20-1122

Towers o f Hanoi, '1 128-1131 redefining base class functions,

an

693 I)y,oon, .9

indirect, 11 18

917-921,939

Q queue (STL t)'pe), 1098- I099

reference, passing by, 356-361, 525

1087- 1088 dequeuing, 1085-1088 dynamic, 108S, 10.93-1099

m

ad

empty, de tecting, 1088 enqueuing, 1085-1088 fi rst-in nrst -O Ul, 1085 full, detecting. 1058 linked list-based, 1093-1096 operations, 1085- 1088 mtic, 1085,1088-1092 QuickSort algorithm, 1131-1135

ss

a pplications of, 1085

array-based,1088-1092 crawling problem with array,

reference variables, 356-361 compared to pointers, 510-51 t reinterpret cast , 700 rdational expression, 164 relational operators, 163-167 reJallonship has-a, 875 is-a, 896, 938-939 whole-pa rt. 875 rcmainder of division, 62-63 rep lac e member func tion, string class, 597 reserved words, 13- 14 r esi ze member function str in9 class, 597 vector, 45 J , 10 14 responsibilities, identi fying, 808 rethro wing an exception, 988-989 return slalement, 32, 330-331, 333 returning a value from a function, 332-342 reusability, 732 reuse, code. 308 reverse member func tion lis t , 1059 ve ctor, 451 , 1014 rewinding a file, 713-7 14 right manipulator, 123-124 rows and columns. arrays, 4 26-427 Ruby, 9 ru nni ng tota l, 280-281 runtime library, 10 rvalue,59

Ha

q ue uc:s, 1085-1096

uh a

m

raising a number to a power, 95- 97 RAM, 4,15 r a nd library function, 133-134 random-access fi les, 706-714 memory, 4, 15 random numbers, 133-134 limiting the ra nge of, 134

seeding, 133

M

time function with, 133 r a ndom_ shuftle algorithm (STL), 10tO, 1014-1016 ranges, numeric, 206 ranking of types, 100-101 reGd member fu nct ion, file Stre:lnl objects, 698-699 read position, fi les, 146

Yo

pseudocode, 19-20 public member functions, 737- 738 public members, class, 736-737 punctuation, 13- 14 pure virtual function, 942

binary search, 11 25-1 127 counting characters, 111 6-11 18 depth of, 1109 direct, 111 8 exhaustive algorithms, 1136-11 38 factorial algorithm, 1112-1 t 15 Fibonacci numbers, 11 20-1122 greatest common divisor (CeO), 111 9-11 20

search trees, bina ry, 1147

az

protected members, 904-.907 prorotype, fu ncrion, 317-318

saenr.ilc nO.s.,on, 54-55

scope. 60-61 , 209-211 block,209 coming into, 2 10 leavi ng, 2 10 local,209 scope resolution operator ( : : ), 740 sea rch algorithm, 467 binary search, 470-473, 1125-1127 linear search, 467-470 sequentia l search, 467

seconda ry storage, 4-5 seekg member function, fi le stream objccts, 706-711 seekp member function, file SHearn objects, 706-711 Selection SOrt, 465--488 sel f-referential data structure, 1029 semicolon, 14,32 scntinels, 283-284 sequence containers, 439, 1007 sequence struclUre, 168 sequential file access, 706 sequential search, 467 set (STl ty pe), 1008 set f member function, cout, ~ee Appendix L on the Student

Ri

loops, 259 promotion, type, 101 prompt, 84

us uf

records, 702-706

1t sraremenr, J73

R

i

Index

CD s e tprecision manipulator,

119-121,680 seiter fu ncrion, 740 setw'manipula tor, 117-118. 125-127,681 s ho r t, 45---46 shon-circuit evaluation, 200, 202 showpoint manipulator, 123 signa turc. funct ion, 363 significant digits, 119 sin librar y fu nction, 131 single precision, 54-55

single tasking, 5 single user operating system, 6 size declarator, arrays, 388, 390 size member function list, 1059 stack, 1083 st ri ng class, 595, 597 vector , 445, 1010 s izeof operator, 58 software, 2, 5-6 application, 5-6 engineering, 21 operating systems, 5-6 sort algorithm (STL). 1010, 1014-1016 sorting, stri ngs, 2 I 7

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

121S

C++,71

m

1007-1008

uh am

binAry_ search algorithm, 1008,1014-1016 contai ners, 1017 count "lgorithm, 1009, 1016-] 017 deque, 1007. 1097- 1098 find algorithm, 1009, 1018- 1019 for each algorithm, 1009.

-1019-1020

M

iterators, 1007-1008,

1010-1013 list, 1007,1 059-1060 map, 1008 max_e l ement alsorithm, 1009,

1016-10 18

az

Yo

us uf

searching within, 573-575 sOfling, 217 string class, 588- 589, 735 Append member functio n, 596 assign member function, 596 at member function, 596 begin member function, 596 capAcity member function. 596 clear member function, 596 compare member function, 597 compa ring and sorting, 590-592 constructors. 593, 778 copy member function, 597 data member function, 597 defining a string ob ject,

Ri

an

ss

sn,

575

strcmp library function, 213- 21 7,

576

strcpy library function, 571-572,

575

stream insertion operator, 33 stream manipulator, 35 st ring appending one to another, 570, 572-573 arrays, 433-435, 568-569 arrays, initia liting with, 403-404 C-string internal storage, 566-569 char array for holding, 88- 89 compa ring with str cmp. 213-217 conearen:Hion, 570, 572-573 constant, 31, 566 copyi ng a C-string, 571-573 functions to handle, writ ing, 582-587 input from keyboa rd, 88-89 length of Csning, getting,

ad

Standard Template Libra ry (ST L), 439,1007- 1018 abstract types, 1007 algorithms, 1008-1010, 1014-1020 aSSOCiative containers,

min_element algorithm, 1009, 1016- 1018 mu l timAp, 1008 multiset , 1008 que ue, 1098- 1099 random_shu!! le algorithm, 1010,1014-1016 sequence containers, 1007 set, 1008 sort algorirhm, 1010, 1014-1016 stack, 1083- 1084 vector, 439-45 1,496- 501, 1007, 101O- 10J 1 state, object, 745 Sla tements, 14- 15 static binding. 929 key word, 827 local variables, 350-353 member functions, 830-833 member variables, 826-830 queues, 1085, 1088- 1092 stacks, 1068- 1075 static_cast, 104- 106 see Standard Template Library s[Qeage, seconda ry, 4-5 strcat library function, 570-571,

Ha

sorting algorithm, 480-481 ascending order, 481 bubble son, 48 1-484 descendi ng order, 481 QuickSort, 1131- 1135 selection sort, 485-488 source code, 10-11 source: file, to-II spccialitcd templates, 1006 specification 61e, class, 753 spreadsheets, 673 sqrt library function, 13 1 srand libra ry function, 133 stAck (STL type), 1083- 1084 empty member function, 1083 pop member fu nction, J083 push member function, 1083 size member function, 1083 top member function, 1083 stacks, 1067-1082 applications of, 1068 array-based, 1068-1075 ca feteria plates, 1067-1068 dynamic, 1068, 1078-1082 iSEmpt y operation, ]069 is Full operation, 1069 L1FO,1067 linked list-based, 1078-1082 math, using for, 1075- 1078 operations, 1068-1069 pop, 1068-1069 push,1068-1069 StallC, 1068-1075 unwinding, 988 stale dara, 748 standard and prestandard

i

Index

569- 570 library functions [Q work with. 569-576 literal, 31, 41-42, 51,566 numeric conversion functions. 577-582 reading with cin, 88- 89

588-589,592-593

empty member function, 597 end member function, 597 e r ase member function, 597 find member function. 597 input, read ing intO a string o bj~ct , 590 insert member function, 597 length member function,

594-595,597 member functions, using, 594-597 operators, supported, 593 replace member function, 597 resize member function, 597 aize member function , 595,597 substr member funnion, 597 swap member function, 597 string header file, 588 st rlen library function, 569-570,

575 strncat library function, 572-573,576 s trncpy library function, 572-573.576 strstr library function, 573-576 struct, 61 J, see also Slfucture structure,61 1 arrays of, 623-626 comparing variables, 618 as constant reference parameters, 633 dynamically allocating, 638-639 as fUllction argument, 630-633 imtializing, 619-622 instances of, 613 members, 612 nested, 626-629 pointers to, 636-640 records, creating with, 702-706 returning from a function,

633-635 sel f-referential, 1029

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH I

U 16

swap member function

string class, 597 vector, 451 swap member function list f 1059

switch sÂŁatement, 222-229 break, 224

case, 222 default , 223 with menus, 227-229 syntax, 13 error, 10

U

objects, 711-713 tellp member fu ncrion, file stream

an

tollg member funct io n , file stream

UM L, see Unified Modeling Language unary operator, 61 underflow, 102-103 Unil1ed Modeling Language (UML), 799-802, 877, See also Appendix ÂŁ on tht Studcm

ss

T tag, structure, 612 tan library function, 131

CD

objects, 7 -1 1-7 13

defini ng objectS of, 1001-1003 inheritance, 1003-1006 prefix, 997-998 specialized,1006 type parameter, 998

M

uh a

m

m

ad

templates, function, 990-997 with multiple types, 994-995 operators, using in, 994 overloading, 995-996 prefi x, 991 type parameter, 991 where to stan, 995-997 ternary operator, 61 teSt expression (for loop), 270-271 t(.)(t editOr, 10-11 this pointer, 848 throw key word, 972, 988 throw poim, 972 throwing an exception, 972 time library function, 133 tolower library function, 563 top-down design, 19 top member functio n, stack, 1083 toupper library function, 563 Towers of Hanoi, 1128-113 1 trailing else, 192.194-195 trailing 1,croes, displaying, 123

access spe<:ific3tion, showing, 800-801 aggregation, showing, 877 class diagram, 799-800 constructors, showing, 802 data type notation, 80 1 destructors, showing, 802 parameter notatiOn, 801 unions, 641-645 anonymous, 641-645 unique member function, list, 1059 United Cause case study, 545-549 unsetf member function, COut, see Appendix L on rht Studem

Ha

templates, class, 997-1006

us uf

Yo

substr member function, string class, 597 subtraction openHor (-), 62, 93-94

V val idation, input, [97,207-208, 261-263 value, passing by, 324-325 value-reTurning functions, 332-342 calling, 334-337 variables, 15-16,39-42 accumulator, 280-281 counter. 263-265 declaration, 16 definition, 16,39-40,60, 209-211 flag, 176-177 global, 344-349 initialization, 60 instance, 825-826 lcgal names, 44 lifetime, 344 local, 333, 342-344 loop comrol, 257 names, 15, 43-44 poimer,509-516 reference, 356-361, 510- 511 scope, 60-61, 209-211 shadowing, 349 static mtmbers, 826-830 vector, 439-451,496-501,1007, 1010-1011 1 1 operator, 441-443, 10ID at melnbcr function, 450, 1013 back member function, 1013 begin member function, 1013 capacity member function, 450, 1013 clear memher function, 447-448,450,10 14 clearing, 447-448 compared to linked list, 1027-1028 defining, 440 empty member function, 448-450,1014 e nd member funcrion, 101 4 erase member function, lOJ4 front member function, 1014 initialization value, 440 insert member function, 1014 pop back member function, ~4 6-447,450, 1010 push _back member function, 443,450,1010 removing elements from, 446-447 resize member hmction, 451, 10 14 reverse member function, 451,10\4

az

style, programming, 69-70,173,259 subscript, array, 389-390

traversing bina ry tret':, 1152-1155 linked list, 1036-1037 true and false values. 166-167.174 rrllncation,56 truth, what is?, 166-167, 174 try block, 973 trylcatch construct, 973-975 try key word, 973 two-dimensiona l arrays, 426-433 initializing, 429 passing to functions, 430-431 summing columns, 432-433 summing elements of. 43J-432 summing rows, 432 type casting, 104-106 coercion, 101 conversion, 101 parameter, 99 1, 998

Ri

structure (colltinlled) strings as members, 618 tag, 612 variable definition, 612-613 stubs and drivers, 369-371

i

Index

CD unsigned im, 45-46 unsigned long, 45-46 unsigned short, 45-46 unwinding the stack, 988 updare expression (for loop), 270-271,275,276-277 uppercase conversion, character, 563-565 USB port, 5 user-com rolled loop, 267, 275-276 using names pace statemcm, 30, 71, see a/so Appendix F on the Studem CD

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1217

while loop, 254-263, 287 body, 255 header, 255 input validation, 261-263 pretest, 257 programming style, 259

objects, 697-698 X

X-Window System, 10

Z

zeroes, [railing, 123

M

uh a

m

m

ad

Ha

ss

an

Ri

az

whitespacc character, 127

width member function, cout and cin. see Appe ndix L on the Student CD word processors, 673 write member function, file stream

Yo

W

whole-part relationship, 875

us uf

Visual C++ 2008 Express Edition, see Appendix M on the Srudem CD void {unctions, 309- 310

searching and sorting, 496-501 size, determining, 445 size member function , 445,1010 starring size, 440 storing and retrieving values in, 441-443 swap member function, 451 virtual destructors, 939-941 virtual function, 929-935, 942 pure, 942 Visual Basic, 9

i

Index

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m

m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Starting Out With C++ From Control Structures through Objects (6th Ed) Tony Gaddis (P3)  

Starting Out With C++ From Control Structures through Objects (6th Ed) Tony Gaddis (P3)

Read more
Read more
Similar to
Popular now
Just for you