15
# 1 1 2 3 Objectives 1. Dynamic Memory 2. Shallow Copy 3. Deep Copy 4. LIFO & FIFO 5. Array Implementation Of A Stack 6. Dynamic Stack 7. Templates 8. Template Stack 9. Primitive Operations Push, Pop, Empty Full, Resize, Overload = 3 4 4 5 5 class Name { public: Name(void); ~Name(void); void Set (char NewFirst[] = "", char NewLast[] = ""); private: int NoCharsInFirstName, NoCharsInLastName; char *First, *Last; }; Name::Name(void) { } 6 Construct A Memory Map [Sketch Of Memory] For Name N1; Initial N1 Map Address Symbolic Name Contents -------------------------------------- | &1000 | *FirstName | ? | -------------------------------------- | &1004 | *LastName | ? | -------------------------------------- | &1008 | NoCharsInFirst | ? | -------------------------------------- | &1012 | NoCharsInLast | ? | -------------------------------------- Not A Good Constructor! Nothing Initialized! Dangling Pointers FirstName & LastName - Pointers Reference Memory Incorrect Memory! 6

Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

  • Upload
    lamanh

  • View
    214

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 1

1 2

3

Objectives1. Dynamic Memory

2. Shallow Copy

3. Deep Copy

4. LIFO & FIFO

5. Array Implementation Of A Stack

6. Dynamic Stack

7. Templates

8. Template Stack

9. Primitive Operations

• Push, Pop, Empty

• Full, Resize, Overload =

34

4

55

class Name{public:

Name(void);~Name(void);void Set (char NewFirst[] = "", char NewLast[] = "");

private:int

NoCharsInFirstName,NoCharsInLastName;

char*First,*Last;

}; Name::Name(void){}

6

Construct A Memory Map [Sketch Of Memory] For Name N1;

Initial N1 Map

Address Symbolic Name Contents --------------------------------------| &1000 | *FirstName | ? |--------------------------------------| &1004 | *LastName | ? | --------------------------------------| &1008 | NoCharsInFirst | ? | --------------------------------------| &1012 | NoCharsInLast | ? |--------------------------------------

Not A Good Constructor!Nothing Initialized!

Dangling PointersFirstName & LastName - Pointers

Reference Memory Incorrect Memory!

6

Page 2: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 2

77

class Person{public:

Person (char NewFirst[] = "", char NewLast[] = ""); ~Person (void);void Set (char NewFirst[] = "", char NewLast[] = "");

private:int

NoCharsInFirstName,NoCharsInLastName;

char*First,*Last;

};

8

Create A Good Constructor For Person P1;

Person::Person (char NewFirst[] = "", char NewLast[] = ""){

};

You Do!

NoCharsInFirstName = strlen(NewFirst)+1;First = new char[NoCharsInFirstName];strcpy(First, NewFirst);NoCharsInLastName = strlen(NewLast)+1;Last = new char[NoCharsInLastName];strcpy(First, NewFirst);

In order to avoid dangling pointers, the constructor should either allocate the needed dynamic memory or set the pointer to NULL.

8

class Person{public:

Person (char NewFirst[] = "", char NewLast[] = ""); ~Person (void);void Set (char NewFirst[] = "", char NewLast[] = "");

private:int

NoCharsInFirstName,NoCharsInLastName;

char*First,*Last;

};

9

Create A Good Destructor For Person P1;

Person::~Person (void){

};

You Do!

delete [] First;delete [] Last;

9

class Person{public:

Person (char NewFirst[] = "", char NewLast[] = ""); ~Person (void);void Set (char NewFirst[] = "", char NewLast[] = "");

private:int

NoCharsInFirstName,NoCharsInLastName;

char*First,*Last;

};

10

Create A Good Memory Map For Person P1 (“Mickey”, “Mouse”);

You Do!

Initial P1 MapAddress Symbolic Name Contents -------------------------------------- -------------------------------| &1000 | *FirstName | &2000 | | &2000-&2006 | Mickey | -------------------------------------- -------------------------------| &1004 | *LastName | &3174 | --------------------------------------| &1008 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1012 | NoCharsInLast | 6 | | &3174-&3180 | Mouse | -------------------------------------- -------------------------------

1111

Initial Donald MapAddress Symbolic Name Contents -------------------------------------- -------------------------------| &1016 | *FirstName | &2400 | | &2400-&2406 | Donald | -------------------------------------- -------------------------------| &1020 | *LastName | &2822 | --------------------------------------| &1024 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1028 | NoCharsInLast | 5 | | &2822-&2826 | Duck | -------------------------------------- -------------------------------

12

Person Mickey (“Mickey”, “Mouse”),Donald (“Donald”, “Duck”);

Initial Mickey MapAddress Symbolic Name Contents -------------------------------------- -------------------------------| &1000 | *FirstName | &2000 | | &2000-&2006 | Mickey | -------------------------------------- -------------------------------| &1004 | *LastName | &3174 | --------------------------------------| &1008 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1012 | NoCharsInLast | 6 | | &3174-&3180 | Mouse | -------------------------------------- -------------------------------

Mickey = Donald;Shallow Copy!

No Operator Overload For =What Happens?

Alter The Memory Maps Accordingly!12

Page 3: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 3

Initial Donald MapAddress Symbolic Name Contents -------------------------------------- -------------------------------| &1016 | *FirstName | &2400 | | &2400-&2406 | Donald | -------------------------------------- -------------------------------| &1020 | *LastName | &2822 | --------------------------------------| &1024 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1028 | NoCharsInLast | 5 | | &2822-&2826 | Duck | -------------------------------------- -------------------------------

13

Initial Mickey MapAddress Symbolic Name Contents -------------------------------------- -------------------------------| &1000 | *FirstName | &2000 | | &2000-&2006 | Mickey | -------------------------------------- -------------------------------| &1004 | *LastName | &3174 | --------------------------------------| &1008 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1012 | NoCharsInLast | 6 | | &3174-&3180 | Mouse | -------------------------------------- -------------------------------

Mickey = Donald; Shallow Copy!

Memory Leak

Shallow copy of Dynamic Variables Creates Memory Leak – When Either Mickey Or Donald Go Out Of Scope, The Destructor Would Cause Other

To Have Dangling Pointers. 1314

Problems With A Shallow Copy

1. Shallow Copy only applies to objects which contain pointers

2. Shallow copy transfers pointer addresses, but fails to properly manage dynamic memory

3. Immediately creates a Memory Leak

If processing occurs in actual memory [like in Windows, MacOS, etc.] re-booting the computer is generally the easiest way to return the lost memory to the Operating System

If processing occurs in a shell [like in UNIX, Linux] logging out and then re-logging in is generally the easiest way to return the lost memory to the Environment.

4.When one of the assignment variables goes out of scope, the destructor for that variable will cause the other assigned variable to have one or more Dangling Pointers.

15

I Hope You Are Asking Yourself?I Hope You Are Asking Yourself?

How Do I Avoid The Problems Generated

By Shallow Copies?

Potential Problem In Many LanguagesNot Unique To C & C++

Must Be Some Solution?16

16

class Person{public:

Name (char NewFirst[] = "", char NewLast[] = ""); ~Name(void);void Set (char NewFirst[] = "", char NewLast[] = ""); void operator = (Person P);

private:int

NoCharsInFirstName,NoCharsInLastName;

char*First,*Last;

};

17

Create A Good Operator Overload For

Person Mickey (“Mickey”, “Mouse”),Donald (“Donald”, “Duck”);

Mickey = Donald;

void Person::operator = (Person P)

{// Fill the Indigenous data

NoCharsInFirstName = P.NoCharsInFirstName;NoCharsInLastName = P.NoCharsInLastName;

// Free the memory associated with First and Last

if (First != NULL)

delete [] First;

if (Last != NULL)

delete [] Last;

Person Mickey (“Mickey”, “Mouse”),Donald (“Donald”, “Duck”);Mickey = Donald;

18

Part 1/2

Page 4: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 4

// Allocate memory for First and fill it with P.First if appropriate

if (N.First == NULL)

First = NULL;

else

{

First = new char [NoCharsInFirstName];

strcpy (First, P.First);

}// Allocate memory for Last and fill it with P.Last if appropriate

if (N.Last == NULL)

Last = NULL;

else

{

Last = new char [NoCharsInLastName];

strcpy (Last, P.Last);

}

}Deep Copy - makes an actual copy of the data to which the pointers are pointing.

19

Part 2/2

There Are Other Solutions!

20

Deep Copy Solves Problems With A Shallow Copy

1. Object has one or more pointers2. Shallow copy transfers pointer addresses and properly manage dynamic memory

3. Creates no Memory Leak4.Creates No Dangling Pointers.

So Why Do We Really Care About This Shallow Copy & Deep Copy Stuff?

Are We Ever Going To Use It?

21 2222

2323

How many of you have ever written a program that had a stack?

What do we ever use a stack for?

LIFO is an acronym for __________________Last In First Out

FIFO is an acronym for __________________First In First Out

A Stack Is A {LIFO/FIFO} Structure ?__________________FIFO

Stack Applet

24

Page 5: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 5

Stack Applethttp://www.sci.brooklyn.cuny.edu/~cis22/animations/tsang/html/STACK/stack800.html

3 Required Primitive Operations For StackPush –Add To Stack

Pop –Remove From Stack

Empty –Is Stack Empty

Optional Primitive Operations For StackStackTop–Peek To See What’s On Top [Peek]

Resize –Resize A Dynamic Memory StackFull –Is Stack Full

25

Stack.hpp

# ifndef STACK_CLASS //============================================

// ----------------------------- Includes -------------------------# include "Utilities.hpp"

// ----------------------------- Defines ---------------------------# define STACK_DIAGNOSTIC_LEVEL 1# define STACK_CLASS

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Class Stack //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////class Stack{//You Do};

# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void TestStack (void);

# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------

# endif //STACK_CLASS ==============================================

Time To Think About Some Code There Are Poor Solutions, Good Solutions, Better Solutions!

26

2727

class Stack1{public:// Constructor// Destructor// Push// Pop// Empty

private:

};

Class Design Should Often Start With The Data!

What Type Of Info Goes Into The Container?Data Structures Are Often Data Driven

long int

What Is The Capacity Of The Container?

6

Need The Info Container?

long intInfo[5],

Info

0

1

2

3

4

5

Need Some Reference To Top?

# define MAX 6

MAXTop;

Top 28

# define MAX 5 class Stack1{public:// Constructor// Destructor// Push// Pop// Empty

private:long int

Info[MAX + 1].Top;

};

Stack1S1,S2;

Design Really Poor Thus Far?

Info

0

1

2

3

4

5

MAX

Top

Info

0

1

2

3

4

5

MAX

TopS1S2

All Stacks HaveTo Be The

Same Exact Size!

We Really Don’t Want To Have To Create One Class

For 6 integers, another for 10

integers, another for 100 integers,

etc.29 30

30

Page 6: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 6

class StackInt{public:

StackInt (long int NewMax = 10);// Destructor// Push// Pop// Empty

private:long int

*Info,Max,Top;

};

StackIntS1,S2(5),S3(100);

What If We Used DynamicMemory & Passed The Size?

Info

Max

TopS1

StackInt Design is BetterThan Stack1 Design?

31

StackInt::StackInt(long int NewMax){

Max = NewMax;Info = new long int [Max + 1];if (Info == NULL){puts (“Out Of Memory In StackInt()”);Max = -1;

}Top = -1; // Empty

};

StackIntS1(5);

The StackInt Constructor

Info

Max

TopS1

Not the best constructor, but it works!

-1

5

&1000

0

1

2

3

4

5

?

?

?

?

?

?

Since we really don’t care, or know what memory block is going to be assigned by

the compiler, we shall abbreviate the memory map as follows: 32

StackInt::~StackInt (void){

if (Info != NULL)delete [] Info;

}

The StackInt Destructor

Max

TopS1

-1

5

Info

0

1

2

3

4

5

?

?

?

?

?

?

33

bool StackInt::Empty (void){

if (Top ==-1)return (true);

elsereturn (false);

}

The StackInt Empty

Max

TopS2

-1

5

Info

0

1

2

3

4

5

?

?

?

?

?

?

Max

TopS1

2

5

Info

0

1

2

3

4

5

A

B

C

?

?

?

S2 is Empty

S1 is not Empty

if (S1.Empty() )

34

bool StackInt::Full (void){

if (Top == Max)return (true);

elsereturn (false);

}

The StackInt Full

Max

TopS2

0

5

Info

0

1

2

3

4

5

A

?

?

?

?

?

Max

TopS1

5

5

Info

0

1

2

3

4

5

A

B

C

D

E

F

S2 is Empty

S1 is not Empty

if (S1.Full() )

Better Than if (Top == Max - 1) 35

bool StackInt::Push (long int NewInfo){

if (Full)return (UNSUCCESSFUL);

else{

Top = Top + 1;Info[Top] = NewInfo;return (SUCCESSFUL);

}}

The StackInt Push

Max

TopS2

0

5

Info

0

1

2

3

4

5

A

?

?

?

?

?

Max

TopS1

5

5

Info

0

1

2

3

4

5

A

B

C

D

E

F

S2 is EmptyS1 is Full

In Utilities.hpp

# define SUCCESSFUL 1# define UNSUCCESSFUL 0or# define SUCCESSFUL true# define UNSUCCESSFUL false

if (S1.Push(B) )

Readability is the Goal!

36

Page 7: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 7

bool StackInt::Pop (long int &OldInfo){

if (Empty)return (UNSUCCESSFUL);

else{

OldInfo = Info[Top];Top = Top -1;return (SUCCESSFUL);

}}

The StackInt Pop

Max

TopS2

0

5

Info

0

1

2

3

4

5

A

?

?

?

?

?

Max

TopS1

5

5

Info

0

1

2

3

4

5

A

B

C

D

E

F

S2 is EmptyS1 is Full

•We will eventually place many things on the stack. •Not all data types can be explicitly returned. •Items are placed on a stack to be used.

if (S1.Pop(B) )

Readability is the Goal!

37

bool StackInt::StackTop (long int&OldInfo)

{if (Empty)

return (UNSUCCESSFUL);else

{OldInfo = Info[Top];return (SUCCESSFUL);

}}

The StackInt StackTop

Max

TopS2

0

5

Info

0

1

2

3

4

5

A

?

?

?

?

?

Max

TopS1

5

5

Info

0

1

2

3

4

5

A

B

C

D

E

F

S2 is EmptyS1 is Full

if (S1.StackTop(C))if (C == ?)

Readability is the Goal!

38

void Stack :: Display(char Message[], long int NoToDisplay) {long int

Postition,DisplayMax;

if (NoToDisplay == -1)

DisplayMax = Max;

else

DisplayMax = Top;

if(strlen(Message) > 0)puts(Message);

for (Postition = DisplayMax; Postition >= 0; Postition--) {

puts(" ------------------------------------------------------");

fflush(stdout);

cout << setw(5) << Postition << "| ";

cout << setw(50) << Info[Postition];

cout << " |\n";

cout.flush();

}

if ((NoToDisplay == -1) || (Top >=0)){

puts(" ------------------------------------------------------");printf(" Top = %3ld Max Stack = %3ld", Top, Max);printf(" Info = & %X\n\n\n", Info);

}

if(Top = -1)

puts("\nStack Is Empty\n");

}

Some type of Displayis essential to proper

diagnostic testing!

39 4040

class StackInt{public:

StackInt (long int NewMax = 10);~StackInt (void);bool Empty (void);bool Full (void);bool Pop (long int & OldInfo);bool Push (long int NewInfo);bool StackTop (long int & OldInfo);

# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="", long int NoToDisplay = 0);

# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------

private:long int

*Info;long int

Max,Top;

}; # ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------

void TestStackInt (void);# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------

# endif //STACK_CLASS ==============================================

Putting It All Together!

Good But Not Great!

Why Not Great?

What If We NeededA Stack For float, char,int, short int, double,

Athlete, Part, Employee, etc.?

41 4242

Page 8: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 8

class StackFloat{public:

StackFloat (long int NewMax = 10);~StackFloat (void);bool Empty (void);bool Full (void);bool Pop ( float & OldInfo);

bool Push ( float NewInfo);

bool StackTop ( float & OldInfo);

# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="", long int NoToDisplay = 0);

# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------

private:float

*Info;long int

Max,Top;

}; # ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------

void TestStackFloat (void);# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------

# endif //STACK_CLASS ==============================================

Change long int to float

Rename Class, Constructor, Destructor

43 4444

class StackChar{public:

StackChar (long int NewMax = 10);~StackChar (void);bool Empty (void);bool Full (void);bool Pop ( char & OldInfo);

bool Push ( char NewInfo);

bool StackTop ( char & OldInfo);

# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="", long int NoToDisplay = 0);

# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------

private:char

*Info;long int

Max,Top;

}; # ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------

void TestStackFloat (void);# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------

# endif //STACK_CLASS ==============================================

Change long int to char

Rename Class, Constructor, Destructor

Could Do Likewise for Employee, short int, double, Athlete, etc.

45 4646

4747

typedef long int InfoType; class Stack{public:

StackInt (long int NewMax = 10);~StackInt (void);bool Empty (void);bool Full (void);bool Pop (InfoType & OldInfo);bool Push (InfoType NewInfo);bool StackTop (InfoType & OldInfo);

# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="", long int NoToDisplay = 0);

# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------

private:InfoType

*Info;long int

Max,Top;

}; # ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------

void TestStackInt (void);# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------

# endif //STACK_CLASS ==============================================

This is even better; only one change is required

to transfer the stack from onedatatype to another.

Many Languages havesome type of TypeDef

Including C & C++

Problem?What if a single

program has two stacks of different

datatypes?

48

Page 9: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 9

4949

5050

51

Templates are used to achieve type-independent logic and abstraction

typedef int T;void Swap (T & Value1, T & Value2){T

Temp;

Temp = Value1;Value1 = Value2;Value2 = Temp;

}

TypeDef Swap Function –Restricted to one Datatype Per Program!

template <class T>void Swap (T & Value1, T & Value2){T

Temp;

Temp = Value1;Value1 = Value2;Value2 = Temp;

}

Template Swap Function –Restricted to one Datatype Per Program!

52

void TestSwap(void){int

A = 5, B = 10;cout << "A = " << A << " B = " << B << endl;Swap (A, B);cout << "A = " << A << " B = " << B << endl;

double AA = 5.5, BB = 5.6;cout << "AA = " << AA << " BB = " << BB << endl;Swap (AA, BB);cout << "AA = " << AA << " BB = " << BB << endl;

char AAA = 'X', BBB = 'O';cout << "AAA = " << AAA << " BBB = " << BBB << endl;Swap (AAA, BBB);cout << "AAA = " << AAA << " BBB = " << BBB << endl;

EmployeeE1(“Road”, “Runner”, 111),E2 (“Roger”, “Rabbit”, 222); E1.Display(“Road Runner”);E2.Display(“Roger Rabbit”);

Swap(E1, E1); E1.Display(“Roger Rabbit”);E2.Display(“Road Runner”);

}

If you have never done a template function, create your own Swap and test it!

Function Template

53

template <class T>void Swap (T & Value1, T & Value2){T

Temp;

Temp = Value1;Value1 = Value2;Value2 = Temp;

}

Templates are not really functions. They are more of a design or pattern for what shall become a function

if evoked.

The compiler shall generate the necessary variations of this function during run time.

Must be placed in .hpp files!

template <class InfoType>class Stack{

...public:

InfoType* Info;

};

Template - Multiple Parameters

54

template <class InfoType, class HeaderNodeType>class Binary Tree{

...};

These did not work properly in GNU C++ twoyears ago.

An important goal of both software engineering and object-oriented

programming is reuse!

Function Templates facilitate code reuse!

Page 10: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 10

5555 56

5757

template <class InfoType> class Stack{public:

Stack (long int NewMax = 10);~Stack (void);bool Empty (void);bool Full (void);bool Pop (InfoType & OldInfo);bool Push (InfoType NewInfo);bool StackTop (InfoType & OldInfo);bool Resize(long int SizeChange = 10);bool operator = (const Stack & S);

# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="", long int NoToDisplay = 0);

# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------

private:InfoType

*Info;long int

Max,Top;

};

Datatype Independent!

If stack is full, attempt to Resize it on the fly!

Deep Copy!

Not Many Changes RequiredTo Get This Generic Solution!

58

template <class InfoType>Stack <InfoType> ::Stack (long int NewMax){# ifdef STACK_DIAGNOSTIC_LEVEL //----------------

if (STACK_DIAGNOSTIC_LEVEL <= 1)puts (“Evoking Constructor Stack(NewMax)”);

# endif // STACK_DIAGNOSTIC_LEVEL ---------------

if (NewMax <= 0)Max = 10;

elseMax = NewMax;

Info = new InfoType [Max];if (Info == NULL){puts (“Out Of Memory In StackInt()”);Max = -1;

}Top = -1; // Empty

}

Stack <char>S1(5);

Really Good Stack Constructor

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Not Many Changes RequiredTo Get This Generic Solution!

Critical Error IfProgrammer AccidentlyCreates An Array Of

Negative Size!

59

Stack <int>IntStack1;

IntStack1.Display(“Contents Of IntStack1”, -1);

IntStack1 shall contain 11 Part elements –the default. Since the built in int class has no initialization in the constructor, the contents of this container is initialized to garbage in memory.

60

Page 11: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 11

Stack <float>FloatStack4(4);

FloatStack5.Display(“Contents Of FloatStack4”, -1);

FloatStack4 shall contain 5 float elements –the default. Since the built in Float class has no initialization in the constructor, the contents of this container is initialized to garbage in memory.

61

Stack <char>CharStack5(5);

CharStack5.Display(“Contents Of CharStack5”, -1);

CharStack5 shall contain 6 char elements. Since the built in char class has no initialization in the constructor, the contents of this container is initialized to garbage in memory.

62

Stack <Student>ClassStack8(8);

ClassStack8.Display(“Contents Of ClassStack8”, -1);

ClassStack8 shall contain 9 Student elements. Since the Student class has a constructor to initialize the data, the contents of this container is initialized accordingly!

63

Stack <Auto>GarageStack9(9);

GarageStack9.Display(“Contents Of GarageStack9”, -1);

GarageStack9 shall contain 10 Auto elements. Since the Auto class has a constructor to initialize the data, the contents of this container is initialized accordingly!

64

template <class InfoType>Stack <InfoType> ::~Stack (void){# ifdef STACK_DIAGNOSTIC_LEVEL //----------------

if (STACK_DIAGNOSTIC_LEVEL <= 1)puts (“Evoking Destructor ~Stack()”);

# endif // STACK_DIAGNOSTIC_LEVEL ---------------

if (Info != NULL)delete [] Info;

}

Really Good Stack Destructor

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Not Many Changes RequiredTo Get This Generic Solution!65

template <class InfoType>bool Stack <InfoType> ::Empty (void){

if (Top ==-1)return (true);

elsereturn (false);

}

Really Good Stack Empty

if (S1.Empty() )

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Not Many Changes RequiredTo Get This Generic Solution!

66

Page 12: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 12

template <class InfoType>bool Stack <InfoType> ::Full (void){

if (Top >= Max)return (true);

elsereturn (false);

}

Really Good Stack Full

if (S1.Full() )

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Not Many Changes RequiredTo Get This Generic Solution!

67

template <class InfoType>bool Stack <InfoType> ::Push (long int NewInfo){

if (Full)if (!Resize() )

return (UNSUCCESSFUL);

Top = Top + 1;Info[Top] = NewInfo;return (SUCCESSFUL);

}

Really Good Stack Push

if (S1.Push(‘B’) )

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Not Many Changes RequiredTo Get This Generic Solution!

“Overflow” –An attempt to exceed theCapacity of the container.

68

template <class InfoType>bool Stack <InfoType> ::Pop (long int &OldInfo){

if (Empty)return (UNSUCCESSFUL);

else{

OldInfo = Info[Top];Top = Top -1;return (SUCCESSFUL);

}}

Really Good Stack Pop

if (S1.Pop(TopInfo) ) S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Not Many Changes RequiredTo Get This Generic Solution!

“Underflow” –An attempt to take more From the container than it contains

69

template <class InfoType>bool Stack <InfoType> :: StackTop (long int &OldInfo){

if (Empty)return (UNSUCCESSFUL);

else{

OldInfo = Info[Top];return (SUCCESSFUL);

}}

Really Good Stack StackTop

if (S1.StackTop(C))if (C == ?)

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Not Many Changes RequiredTo Get This Generic Solution!

70

Really Good Stack Display

Not Many Changes RequiredTo Get This Generic Solution!

Our Display Is Only Used During Testing!//# define STACK_DIAGNOSTIC_LEVEL 1

It Can Only Be Used To Display Those Classes That Overload <<

# ifdef STACK_DIAGNOSTIC_LEVEL //---------------------------------------------------

template <class InfoType>

void Stack <InfoType> :: Display(char Message[], long int NoToDisplay) {long int

Postition,DisplayMax;

if (NoToDisplay == -1)

DisplayMax = Max;else

DisplayMax = Top;

if(strlen(Message) > 0)puts(Message);

for (Postition = DisplayMax; Postition >= 0; Postition--) {

puts(" ------------------------------------------------------");fflush(stdout);cout << setw(5) << Postition << "| ";cout << setw(50) << Info[Postition]; cout << " |\n";cout.flush();

} if ((NoToDisplay == -1) || (Top >=0)){

puts(" ------------------------------------------------------");printf(" Top = %3ld Max Stack = %3ld", Top, Max);printf(" Info = & %X\n\n\n", Info);

}

if(Top = -1)

puts("\nStack Is Empty\n");

}

# endif // STACK_DIAGNOSTIC_LEVEL --------------------------------------------------

71

template <class InfoType>bool Stack <InfoType> :: Resize (long int SizeChange){long int

Pos,NewMax = Max + SizeChange;

InfoType* NewInfo;

// Create New Block Of MemoryNewInfo = new InfoType [NewMax + 1];if (NewInfo == NULL)

return (UNSUCCESSFUL);

// Copy Data To New Block Of Memoryfor (Pos = 0; Pos <= Max; Pos ++)

NewInfo[Pos] = Info[Pos];

// Update Other Stuffdelete [] Info;Info = NewInfo;Max = NewMax;return (SUCCESSFUL);

}

Marginally OK Stack Resize

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Assumes SizeChange is Positive!What if pass Negative SizeChange?

// Can't make array smallerif (SizeChange < 1)

return (UNSUCCESSFUL);

72

Page 13: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 13

If we do not overload the = operator, then we would have the following Shallow Copy

73

Shallow Copy generates

Memory Leak

74

overload = operator,

Deep Copy

75

Deep Copy Returned Memory

& 7F0894

No Memory Leak

76

template <class InfoType> void Stack <InfoType> :: operator = (const Stack & S){long int

Pos;InfoType

* NewInfo;

// Create Properly Sized Info ContainerNewInfo = new InfoType [S.Max + 1];if (NewInfo == NULL)

return;

// Free the memory associated with Info if (Info != NULL)

delete [] Info;

Max = S.Max;Top = S.Top;Info = NewInfo;

// Copy Infofor (Pos = 0; Pos <= Max; Pos ++)

Info[Pos] = S.Info[Pos]; }

Good Stack operator = Overload

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

77

Athlete Trinity[50];

long intPos;

Stack <Athlete>CSCI2320 (3), CSCI3343(3);

Trinity[1].Set ("Sarah", 1001, 1, 11.11), Trinity[2].Set ("Michael", 1002, 11, 22.22), Trinity[3].Set ("Rebecca", 1002, 2, 33.33), Trinity[4].Set ("Thomas", 1004, 12, 44.44);

for (Pos = 1; Pos <= 4; Pos++)CSCI2320.Push(Trinity[Pos]);

CSCI2320.Display("CSCI2320 is full with 4", -1);CSCI3343.Display("CSCI3343 is Empty With 10", -1);

CSCI3343 = CSCI2320;

Copy Constructor

The Deep Copy Assignment is necessary and essential, but if the only objective is only to create one Stack that is a duplicate of the other, why take the time to initialize a stack –only to destroy it and copy it.

Most ADT’suse a Copy Constructor to save that wasted effort.

Stack <Athlete>CSCI2320 (CSCI2320);

Stack (const Stack & S);

Class Prototype Left As An Exercise For You!78

Page 14: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 14

Stack <int>Quatity (4);

Stack <char>Prefix (10);

Stack <float>Cost (3);

Stack <Book>TU_Library (6000),BookStop;

Stack <Client>SmithBarney (5),DataAbstractions;

Stack <Part>Inventory (-5),SearsWarehouse;

Stack <Athlete>Football(40),Softball(33);

Testing –All in the same program

S1

Info

Max

Top-1

5

0

1

2

3

4

5

?

?

?

?

?

?

Not Possible With one Block Of Class Code In Most Languages!

79

Remember The Microsoft Office Example

80

Structured LanguageDeveloped Windows Version FirstMac Version Cost 88% of Windows Version

C++Developed Windows Version FirstWrote Parallel Versions Of A Few Short Utilities To Open/Close File, Move Cursor To Row/Col, Minimize Window, etc. using the basic operating system calls.Mac Version Ran In One Day –had to tweek screen because of different pixel resolution –alter images on user manual.

Function Overloads Operator Overloads .hpp & .cpp Separation Stream overloads

Templates

80

8181

82

82

83

83

8484

Page 15: Objectives - Computer Science | Inside.Trinity.educs.trinity.edu/~thicks/2320-2004-S/Lecture-PDF/Stack.pdf · Objectives 1. Dynamic Memory 2. Shallow Copy 3. ... (“Mickey”, “Mouse”);

# 15

Dynamic Memory Allocation 1short int

E, // Variable E contains garbage*F; // Pointer F contains garbage

E = 5;// To display the contents of container E

printf (" E = %d\n", E);

// To display the where container E is stored in memory (i.e. the address of E)printf (" &E = %ld = %x \n", &E, &E);

// To display the sizeof container E (i.e. 2)printf (" sizeof(E) = %ld bytes \n", sizeof(E));

// To display where pointer F is stored in memory (i.e. the address of F)printf (" &F = %ld = %x\n", &F, &F);

// To display the sizeof container F (i.e. 4)printf (" sizeof(F) = %ld bytes \n", sizeof(F));

// To make pointer F point to variable E memory containerF = & E;

// To display the memory pointed to by pointer F (i.e. variable E = 5)printf (" *F = %d\n", *F);

// To change the value of the memory pointed to by F to 32766 (i.e. E to 32766)(*F) = 32766;printf (" E = %d\n", E);printf (" *F = %d\n", *F);

// To increase the value of E(*F)++;E++;

E = 5&E = 1245052 = 12ff7c sizeof(E) = 2 bytes &F = 1245048 = 12ff78sizeof(F) = 4 bytes *F = 5E = 32766*F = 32766

85

Dynamic Memory Allocation 2

char *F; // Pointer F contains garbage

// To display the garbage memory associated with Fprintf ("1 F = %ld = %x\n", F, F); // Garbage in memory

// To allocate 1 character of memory for FF = new char;printf ("2 F = %ld = %x\n", F, F); // NULL if no memory

// To display the sizeof container F (i.e. 4)printf ("3 sizeof(F) = %ld bytes \n", sizeof(F));

// To change the value of the memory pointed to by F to 'A')(*F) = 'A';printf ("4 *F = %c\n", *F);printf ("5 *F = %d\n", *F); // ASCII Value of A

// To increment the value of the memory pointed to by F(*F)++;printf ("6 *F = %c\n", *F);

// To return the memory associated with pointer Fdelete F;printf ("7 F = %ld = %x\n", F, F); // Dangling/Stale PointerF = NULL;printf ("8 F = %ld = %x\n", F, F); // Good computer scientist assigns ptrs NULL

1 F = -858993460 = cccccccc2 F = 4457376 = 4403a03 sizeof(F) = 4 bytes 4 *F = A5 *F = 656 *F = 667 F = 4457376 = 4403a08 F = 0 = 0

86

short int E = 1,*F;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");puts ("\nMake F Point To Container E\n");F = & E;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");puts ("\nUse Pointer F to Change Memory Associated With It\n");(*F) = 32766;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");puts ("\nTwo Ways To Change Memory associated with variable E\n");E++;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");puts ("\nMax Value For 2 Byte [2's Complement] = 32767 - Overflow E\n");E++;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");

Dynamic Memory Allocation Memory Map Code

void SketchShortInt(short int ContainerContents, short int * ContainerAddress, char ContainerName[])

{printf (" %-3s - %ld Bytes - short int\n", ContainerName, sizeof(short int));printf (" |--------------------------------|\n");// Print Contents in Decimal and then Hexadecimalprintf (" | %14d | %13x |\n", ContainerContents, ContainerContents);printf (" |--------------------------------|\n");// Print Address in Decimal and then Hexadecimalprintf (" &%ld - &%x\n\n", ContainerAddress, ContainerAddress);

}

void SketchShortIntPtr(short int * ContainerContents, short int ** ContainerAddress, char ContainerName[])

{printf (" %-3s - %ld Bytes - short int*\n", ContainerName, sizeof(short int*));printf (" |----------------------------------------------------|\n");printf (" | %50d |\n", ContainerContents);printf (" |----------------------------------------------------|\n");printf (" &%ld - &%x\n\n", ContainerAddress, ContainerAddress); //Address Decimal - Hex

}

87