1 CSC241: Object Oriented Programming Lecture No 25.

Slides:



Advertisements
Similar presentations
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
Advertisements

Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
1 Templates Chapter What You Will Learn Using function templates to created a group of overloaded functions Using class templates to create a group.
Procedural programming in Java
AU/MITM/1.6 By Mohammed A. Saleh 1. Arguments passed by reference  Until now, in all the functions we have seen, the arguments passed to the functions.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
Rossella Lau Lecture 11, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 11: Template and Operator overload  Template.
 2006 Pearson Education, Inc. All rights reserved Templates.
Using Templates Object-Oriented Programming Using C++ Second Edition 11.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
1 CSC241: Object Oriented Programming Lecture No 07.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Intro to Generic Programming Templates and Vectors.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
1 CSC241: Object Oriented Programming Lecture No 13.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CHAPTER 3 Function Overloading. 2 Introduction The polymorphism refers to ‘one name having many forms’ ‘different behaviour of an instance depending upon.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Templates An introduction. Simple Template Functions template T max(T x, T y) { if (x > y) { return x; } else { return y; } } int main(void) { int x =
Procedural programming in Java Methods, parameters and return values.
Computer Engineering Rabie A. Ramadan Lecture 5.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Lecture 17 Templates, Part I. What is a Template? In short, it’s a way to define generic functionality on parameters without needing to declare their.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
March 2006 Copyright, 2006 Oxford Consulting, Ltd C++ Templates Templates F Part of the ongoing development of the C++ language F Integral part.
1 Using Templates COSC 1567 C++ Programming Lecture 10.
CS212: Object Oriented Analysis and Design
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Chapter -6 Polymorphism
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
C++ Functions A bit of review (things we’ve covered so far)
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Data Structure Lecture 1.  The Logical Organization of Data is called data structures  organize data  more efficient programs.  More powerful computers.
MAITRAYEE MUKERJI Object Oriented Programming in C++
Programming with ANSI C ++
C++ Templates.
Templates.
Object Oriented Programming Mansoor Ahmed Bughio
Generic programming – Function template
CS212: Object Oriented Analysis and Design
Lecture 22 Inheritance Richard Gesick.
Templaets It is a new concept which enables us to define “generic class “ and “generic function” to provide the “ generic programming” We are familiar.
CMSC 202 Lesson 22 Templates I.
Templates Class Templates
Miscellaneous C++ Topics
Templates I CMSC 202.
Templates An introduction.
ENERGY 211 / CME 211 Lecture 23 November 12, 2008.
Templates CMSC 202, Version 4/02.
Presentation transcript:

1 CSC241: Object Oriented Programming Lecture No 25

2 Previous Lecture Example programs – Publication company Two derived classes – Book and Tape Polymorphic behavior: Virtual function – Distance class Overloaded * operator Friend version of member function required one more argument

3 Today’s Lecture Intro to Generic Programming – Template Function template Class template

4 Generic programming There are situations where same algorithms works for different data type – Suppose a function that returns the maximum of two numbers Same algorithm (to find the max number) works with integers and real numbers – Until now we have to write two separate function int max (int, int); float max (float, float); – Through generic programming we can have just one function to find max of int or float or any other type of values

5 Cont. Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameter So if max() function is called with int parameter, max function with int parameter is created In C++ generic programming is implemented with “templates

6 Benefit of generic programming Reusability Value Max (Value1, Value2) { if( Value1 > Value2 ) return Value1; else return Value2; } Value Max (Value1, Value2) { if( Value1 > Value2 ) return Value1; else return Value2; } y= Max(15, 67); int Max (int arg1, int arg2) { if( 15 > 67 ) return arg1; else return arg2; } int Max (int arg1, int arg2) { if( 15 > 67 ) return arg1; else return arg2; } y= Max(15.45, 67.45); int Max (float arg1, float arg2) { if( 15 > 67 ) return arg1; else return arg2; } int Max (float arg1, float arg2) { if( 15 > 67 ) return arg1; else return arg2; }

7 Templates Templates make it possible to use one function or class to handle many different data types The template concept can be used in two different ways: – with functions and – with classes

8 A simple function template Suppose we want to write a function that returns the absolute value of two numbers absolute value of a number is its value without regard to its sign: – absolute value of 3 is 3 – absolute value of –3 is also 3 – absolute value of 4.5 is 4.5 – absolute value of -4.5 is 4.5

9 Why Template Observations: Same algorithm: body of function is same in each case But they are completely different functions because they handle different types of arguments and return values Time-consuming and wastes space Using template you need to write such a function just once, and it works for many different data types int abs(int n) { return (n<0) ? (-1*n) : n; } int abs(int n) { return (n<0) ? (-1*n) : n; } long abs(long n) { return (n<0) ? (-1*n) n; } long abs(long n) { return (n<0) ? (-1*n) n; } float abs(float n) { return (n<0) ? (-1*n) : n; } float abs(float n) { return (n<0) ? (-1*n) : n; }

10

11 Template version of abs function Key feature: represent the data type used by the function i.e. T. It is also called template argument keyword class might just be called type, as user define class also represent new type template T abs(T n) { return (n<0) ? -1*n : n; } template T abs(T n) { return (n<0) ? -1*n : n; } function template

12 What the Compiler Does At compile time: – Compiler do nothing for template function – It cannot generate code as it don’t know type – It remember template function for future reference Code generation of template function take place when that function is invoked Now compiler know that type is int So it generates a specific version of the abs() function for type int int x=-3, y; y = abs (x); int x=-3, y; y = abs (x);

13 template T abs(T n) { return (n < 0) ? (-1*n) : n; } main() { int int1 = 5, int2 = -6; long lon1= 70000, lon2 = , double dub1 = 9.95, dub2 = ; } Program Output Example Program – abs function cout << abs(int1); cout << abs(int2); cout << abs(lon1); cout << abs(lon2); cout << abs(dub1); cout << abs(dub2); int abs(int n) { return (n<0) ? (-1*n) : n; } int abs(int n) { return (n<0) ? (-1*n) : n; } long abs(long n) { return (n<0) ? (-1*n) n; } long abs(long n) { return (n<0) ? (-1*n) n; } double abs(double n) { return (n<0) ? (-1*n) : n; } double abs(double n) { return (n<0) ? (-1*n) : n; } Go to program

14 Simplifying source file Amount of RAM used is same – whether template approach is used or – actually write three separate functions Template approaches simply saves from having three separate functions into the source file This makes the source file shorter and easier to understand For any change in function, the change should be make in only one place in the source file instead of three places

15 Example program 2 Write a program that can sort int, float, double, character and etc type of array in ascending order and then display it. Write a program

16 Function Templates – Multiple Arguments Suppose a function to search an array for a specific value This function takes three arguments: – two that are template arguments – one of a basic type Function returns the array index for that value if it finds it, or –1 if it can’t find it

17 template int find(atype* array, atype value, int size) { for(int j=0; j<size; j++) if(array[j]==value) return j; return -1; } char chrArr[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’}; char ch = ‘d’; int intArr[] = {1, 3, 5, 9, 11, 13}; int in = 6; long lonArr[] = {1, 3, 5, 9, 11, 13}; long lo = 11; double dubArr[] = {1.0, 3.0, 5.0, 9.0, 11.0, 13.0}; double db = 4.5; main() { cout << “\n d in chrArray: index=” << find(chrArr, ch, 6); cout << “\n 6 in intArray: index=” << find(intArr, in, 6); cout << “\n11 in lonArray: index=” << find(lonArr, lo, 6); cout << “\n 4 in dubArray: index=” << find(dubArr, db, 6); } Program Output d in chrArray: index=3 6 in intArray: index=-1 11 in lonArray: index=4 4 in dubArray: index=-1 Go to program

18 Template Arguments Must Match When a template function is invoked, all instances of the same template argument must be of the same type. For example, in find(), if the array name is of type int, the value to search for must also be of type int. Following code give and error message int intarray[] = {1, 3, 5, 7}; float f1 = 5.0; int value = find(intarray, f1, 4); because the compiler expects all instances of atype to be the same type. It can generate a function find( int*, int, int); but it can’t generate find( int*, float, int);

19 More Than One Template Argument template btype find( atype * array, atype value, btype size) { for(btype j=0; j<size; j++) //note use of btype { if(array[j]==value) return j; } return (btype)(-1); } int a[5] = {4, 3, 2, 6, 7}, y, b=3; y = find ( a, b, 5 ); int a[5] = {4, 3, 2, 6, 7}, y; float b=3.5; y = find ( a, b, 5 );

20 Why not marcos? Macros can be used to create different versions of a function for different data types. #define abs(n) ( (n<0) ? (-1*n) : (n) ) It performs a simple text substitution and can thus work with any type Problem: – macros don’t perform any type checking – Compiler wouldn’t check if several argument of marcos are of same type or not – Return value type is not specified

21 What type works? How to determine that a template function can be instantiated for a particular data type? E.g. can find function works with c-strings type