Reusing Code Public inheritance is one mechanism. Class template Using class member which are object of other classes. ( containment, composition or layering).

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
CS 240Chapter 6 - StacksPage 21 Chapter 6 Stacks The stack abstract data type is essentially a list using the LIFO (last-in-first-out) policy for adding.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
Pointers1 Pointers & Dynamic Arrays Allocating memory at run-time.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
Data Structures Chapter 2 Stacks Andreas Savva. 2 Stacks A stack is a data structure in which all insertions and deletions of entries are made at one.
Basic Elements of C++ Chapter 2.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Review of C++ Programming Part II Sheng-Fang Huang.
Object Oriented Data Structures
CS 1031 C++: Object-Oriented Programming Classes and Objects Template classes Operator Overloading Inheritance Polymorphism.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Templates Zhen Jiang West Chester University
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
1 Linked Stack Chapter 4. 2 Linked Stack We can implement a stack as a linked list. Same operations. No fixed maximum size. Stack can grow indefinitely.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Pointers OVERVIEW.
Introduction to Stacks Chapter 2. Objectives Introduce abstract data types. Discuss implementation types. – Static – Dynamic – Contiguous Introduce the.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
Object-Oriented Programming in C++
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 CS 132 Spring 2008 Chapter 7 Stacks Read p Problems 1-7.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
11 Introduction to Object Oriented Programming (Continued) Cats.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
Overview of Previous Lesson(s) Over View 3  CLR Programming  Common Language Runtime (CLR) is a programming, that manages the execution of programs,
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
C++ Lesson 1.
Template Classes.
Chapter 22 - C++ Templates
CS212: Object Oriented Analysis and Design
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CS150 Introduction to Computer Science 1
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

Reusing Code Public inheritance is one mechanism. Class template Using class member which are object of other classes. ( containment, composition or layering). private or protected inheritance,

Class Template

Stack and Queue are examples of container classes,( to hold other objects or data types). We can define stack and queue class as generic type. Define as Template. Consider the stack class as follow :

typedef unsigned long Item; class Stack { private : enum {MAX=10}; Item items[MAX]; // stack items int top; public : Stack(); bool isempty(); bool isfull(); bool push( const Item & item); bool pop( Item & item); // pop top into item };

#ifndef STACKP_H_ #define STACKP_H_ template // template // It doesn’t mean that Type must be a class class Stack { private : enum {MAX=20}; Type items[MAX]; // stack items int top; public : Stack(); bool isempty(); bool isfull(); bool push( const Type & item); bool pop( Type & item); // pop top into item };

template Stack :: Stack() { top=0; } template bool Stack :: isempty( ) { return top==0; } template bool Stack :: isfull( ) { return top==MAX; }

template bool Stack :: push(const Type & item) { if( top < MAX) { items[top++]=item; return true; } else return false; }

template bool Stack :: pop( Type & item) { if( top > 0) { item=items[--top]; return true; } else return false; } #endif

If the compiler supports export keyword we can put the stack definition class in a separate file as follow : #ifndef STACKP_H_ #define STACKP_H_ export template class Stack { …. }; and the rest as usual. OTHEWISE place the template class definitions and header file together, in a same file.

In this example we want to print all sequences of 1,2,3,…,n which can be obtained by push and pop operator. We have sequence 1,2,3,…,n, each time either we read one number (from left to right) and push to stack, or we don’t read any number and we pop a number from stack and we print it. For example by applying, push push pop push pop, pop on sequence 1,2,3 we get output We can’t get from push and pop.

#include #include “stackp.h” Stack st; void stacki_string(int n, int flag, int Max_size, int *array); int main() { int n; cout<<“ enter a positive integer n”; cin>>n; int * array=new int[2*n]; stacki_string(0,0,2*n, array); return 0; }

void stacki_string(int n, int flag, int Max_size, int *arr) { if( flag (Max_size-n) ) return; if( n== Max_size) { int i; int j=1; int top_item; for( i=0; i<n; i++) { if ( arr [i] ==1) { st.push(j); j++; } if( arr[i] == 0) { st.pop(top_item); cout<<top_item<<“ “; }

cout<<endl; return; } arr[n]=1; stacki_string(n+1, flag+1,Max_size,arr); arr[n]=0; stacki_string(n+1, flag-1,Max_size,arr); }

Question ? Given a sequence of number, decide whether it can be obtained by series of push and pop? If yes, how?

Using stack of pointers #ifndef STACKP1_H_ #define STACKP1_H_ template class Stack { private : enum {SIZE=20}; //defualt size const int stacksize; Type * items; //holds stack items int top; public : explicit Stack(int ss=SIZE); // If we don’t use explicit the implicit conversion happens Stack(const Stack & st); ~Stack( ) { delete [ ] items; }

bool isempty() {return top==0; } bool isfull() {return top==stacksize ; } bool push( const Type & item); bool pop( Type & item); // pop top into item Stack & operator=(const Stack & st); }; template Stack :: Stack(int ss) : stacksize(ss), top(0) { items=new Type[stacksize]; }

// copy constructor template Stack :: Stack(const Stack &st ) { stacksize=st.stacksize; top=st.top; delete[ ] items; items=new Type[stacksize]; for( int i =0; i< top; i++) items[i]=st.items[i]; }

template bool Stack :: push(const Type & item) { if( top < stacksize) { items[top++]=item; return true; } else return false; }

template bool Stack :: pop( Type & item) { if( top > 0) { item=items[--top]; return true; } else return false; }

// overloading the assignment operator we use dynamic //memory allocation template Stack & Stack ::operator= (const Stack & st) { if( this == &st) return *this; delete [ ] items; stacksize = st.stacksize; top=st.top; items = new Type[stacksize]; for( int i=0; i< top; i++) items[i]=st.items[i]; return *this; } #endif

#include #include “stackp1.h” const int Num=10; int main() { srand(time(0)); // randomize rand() cout<<“Please enter stack size”; int stacksize; cin>>stacksize; Stack st(stacksize); const char * in[Num]={ “1: Dave Cohen”, “2: Anders Yeo”, “3: Gregory Gutin”, “4: Allan Davis”, “5: Janet Hales”, “6: Amanda Baker”, “7 : Martin Green”, “8: Bob Vickers”, “9: Alex Clark”, “10: liz Hogger” };

const char * out[Num]; int processed =0; int nextin=0; while( processed < Num) { if(st.isempty()) st.push(in[nextin++]); else if (st.isfull()) st.pop(out[processed++]); else if ( rand() %2 && nextin < Num) st.push(in[nextin++]); else st.pop( out[processed++]); } for(int i=0; i<Num;i++) cout<<out[i]<<endl; return 0; }

Run : Please enter stack size:10 2: Anders Yeo 1: Dave Cohen 3: Gregory Gutin 5: Janet Hales 4: Allan Davis 7: Martin Green 9: Alex Clark 8: Bob Vickers 6: Amanda Baker 10: liz Hogger

Please enter stack size:5 3: Gregory Gutin 5: Janet Hales 6: Amanda Baker 4: Allan Davis 8: Bob Vickers 9: Alex Clark 10: liz Hogger 7: Martin Green 2: Anders Yeo 1: Dave Cohen

Array Template Using template argument to provide the size of a regular array rather than dynamic array.

#ifndef ARRAYTP_H_ #define ARRAYTP_H_ #include template class ArrayTP { private : T ar[n]; public : ArrayTP() { }; explicit ArrayTP( const T &v); virtual T & operator[ ]( int i); virtual T operator[ ]( int i) const; };

template ArrayTP ::ArrayTP (const T & v) { for(int i=0; i<n;i++) ar[i]=v; }; template T & ArrayTP ::operator[ ]( int i) { if( i =n) { cout<<“error in array lim “<<“ out of rang “<<endl; exit(1); } return ar[i]; }

template T ArrayTP ::operator[ ]( int i) const { if( i =n) { cout<<“error in array lim “<<“ out of rang “<<endl; exit(1); } return ar[i]; } #endif

#include #include "arraytp.h" int main() { ArrayTP sample; ArrayTP sample1(5.5); int i; for(i=0; i< 10; i++) cout<<sample1[i]<<" "; double *pt; pt=&sample1[4]; *pt=7.7; for(i=0; i< 10; i++) cout<<sample1[i]<<" "; cout<<endl; return 0; }

template Here int n is called non-type or expression,argument. ArrayTP sample; compiler defines a class called ArrayTP and sample is an object of it. An expression argument can be an enumeration type, a reference, a pointer. Not a double, but double &rm or double *pm are allowed. We can’t alter the value of expression argument.

When we instantiate a template, the value used for the expression argument should be a constant expression. The expression argument has no advantage over the constructor approach. CA approach uses heap memory and EA uses the memory stack for automatic variables which is faster in run time.

Template class as base class template class Array { private : T entry; …. };

template class Growarray : public Array {…}; // inheritance template class Stack { Array ar; //use an array <> as a component … }; … Array > asi; // an array of stack of int

ArrayTp, 10 > tw; What is tw;

ArrayTp, 10 > tw; tw is an array of 10 element, each is an array of five int. is the same as int tw[10][5];

Write a program based on Graphical User Interface (GUI) using Microsoft Visual Studio C to model the registration of students for university courses. Students request courses and the university offers courses. Your program handles the the requests and offers.

Students submit a single application which includes requests for registration in chosen courses. The university offers vacancies in courses any number of times. Student requests are always considered in the order in which their applications were received. Students can register for a maximum of ten courses.

Because the number of vacancies in courses is limited they may apply for any number of courses. If vacancies are available they are registered in these courses in descending order of preference up to a maximum of ten courses. Each time vacancies in courses are offered by the university, the requests of each student are reviewed in the order of preference specified by each student and in the order in which student applications were received.

If a student is registered for the maximum number of course when a vacancy is offered in a course which has higher preference than one of the courses in which he is already registered then he is registered for the higher preference course and his lowest preference registration is cancelled and this newly released course vacancy is offered to other students on the next round.

Program Inputs Students’ registration requests and university course vacancy offers are input from the keyboard via appropriate GUI controls. You are responsible to design your GUI to allow your application to take inputs only via GUI. Usability The user can also request various reports describing the state of the system. All output is written to appropriate GUI control tools. Note that output is produced only in response to the user's request for reports.

Main Interface The front page of your GUI must support the following services: –Course Offer –Registration Request –Student Report –Course Report –Course Summary –Student Summary –Quit Please Select Service….

Sample Input Command: Course Offer CMPT212 (Course code) Object Oriented Cooking (Course title) 100 (Number of places offered) (Cost of course)

Command: Registration Request R (Student registration number) Moyo, J (Student name) BSc (Student degree) CMPT123 (Student course request) CMPT234 (Student course request) CMPT110 (Student course request) (Any number of courses may be requested)

Command: Student Report Request R123456A (For student registration number) CMPT212 (for course code) Command: Course Report Request CMPT212 (for course code) Command: Course Summary Request Command: Student Summary Request

Output Reports The Student Report Request command above should produce a report similar to the following sample: R123456A Moyo, J BSc $ Registered: CMPT123 CMPT234 MATH567

The Course Report Request command above should produce a report similar to the following sample: CMPT212 Pure Object Oriented Programming () Offered: 100 Registered: 50

The Course Summary Request command above should produce a report similar to the following sample showing the total number of students currently registered for each course and the total cost of offering the course (computed from the number of students registered for the course multiplied by the course fee): Code Registration Total Cost CT CT XY

The Student Summary Request command above should produce a report similar to the following sample showing each student, degree, number of courses registered for and total cost of those courses: ID Number Degree #Courses Fee R123456A BSc R234567B MSc

Submission Date 30th July % of the total mark.