Download presentation
Presentation is loading. Please wait.
Published byMargaretMargaret Bradford Modified over 7 years ago
1
Lecture 25 OOP. Parameterized Abstract (User Defined) Data Types
COS220 Concepts of PLs AUBG, COS dept Lecture 25 OOP. Parameterized Abstract (User Defined) Data Types Reference: Sebesta, Chaps 9,11; Sec 9.8.2 Friedman&Koffman, Sec 11.3 5/9/2018 Assoc. Prof. Stoyan Bonev
2
More on data conversion and cast operators in C++
.
3
Assoc. Prof. Stoyan Bonev
Type conversion in C++ Given a program to treat expressions involving several different data types. As an example, consider this program with mixed type expressions: void main() { int count = 7; float avgWeight = 155.5F; double totalWeight = count * avgWeight; cout << “totalWeight=” << totalWeight << endl; } Here a variable of type int is multiplied by a variable of type float to yield a result of type double. This program compiles without error; the compiler considers it normal that you want to multiply numbers of different types. 5/9/2018 Assoc. Prof. Stoyan Bonev
4
Automatic conversions in C++
what happens when the compiler confronts mixed-type expressions. Types are considered into hierarchy from “higher” to “lower” Data Type Order long double Highest double float long int short char Lowest 5/9/2018 Assoc. Prof. Stoyan Bonev
5
Automatic conversions in C++
The arithmetic operators like + and * like to operate on two operands of the same type. When two operands of different types are encountered in the same expression, the lower-type variable is converted to the type of the higher-type variable. Thus, the int value of count is converted to type float and stored in a temporary variable before being multiplied by the float variable avgWeight. The result (still of type float) is then converted to double so that it can be assigned to the double variable totalWeight. This process is shown on next slide. 5/9/2018 Assoc. Prof. Stoyan Bonev
6
Automatic conversions in C++
. 5/9/2018 Assoc. Prof. Stoyan Bonev
7
Assoc. Prof. Stoyan Bonev
More on casts in C++ In C++ the term cast applies to data conversions specified by the programmer, as opposed to the automatic data conversions known as implicit conversions like intVar = doubleVar; Casts are also called type casts. What are casts for? In case you need to convert a value from one type to another in situation where the compiler will not do it automatically or will not do it without complaining. 5/9/2018 Assoc. Prof. Stoyan Bonev
8
Assoc. Prof. Stoyan Bonev
More on casts in C++ There are several kinds of casts in Standard C++: Static casts Dynamic casts Reinterpret casts Const casts 5/9/2018 Assoc. Prof. Stoyan Bonev
9
Static casts .
10
Assoc. Prof. Stoyan Bonev
Static casts C++ casts look like this statement. vari = static_cast<int>(varf); Here the variable to be cast (varf) is placed as argument in parentheses and the type it’s to be changed to (int) is placed in angle brackets. The result is that varf is changed to int before it is assigned to vari. 5/9/2018 Assoc. Prof. Stoyan Bonev
11
Assoc. Prof. Stoyan Bonev
Static casts Another example of C++ cast. chVar = static_cast<char>(vari); Here the variable to be cast (vari) is placed as argument in parentheses and the type it’s to be changed to (char) is placed in angle brackets. The result is that vari is changed to char before it is assigned to chVar. 5/9/2018 Assoc. Prof. Stoyan Bonev
12
Assoc. Prof. Stoyan Bonev
Static casts Example: suppose a program with intermediate result that exceeds the capacity of the int or unsigned variable type, resulting in wrong result. In other words, intermediate result won’t fit the int or unsigned type either. 5/9/2018 Assoc. Prof. Stoyan Bonev
13
Assoc. Prof. Stoyan Bonev
Static casts Example: suppose a program with intermediate result that exceeds the capacity of the variable type, resulting in wrong result. In other words, intermediate result won’t fit the int or unsigned type either. int Vari = ; // 1,500,000,000 Vari = (Vari * 10) / 10; cout << endl << "Vari = " << Vari; When we multiply variable Vari by 10, i.e. 1,500,000,000 * 10, the result is 15,000,000,000 and it is too large to fit in integer variable 5/9/2018 Assoc. Prof. Stoyan Bonev
14
Assoc. Prof. Stoyan Bonev
Static casts In order to get safe result, we can redefine the Vari data type from int to double or float. But suppose for some reason, such as keeping the program size small, we don’t want to change the variable to double. In this case here is the solution: We can cast Vari to type double before multiplying Vari = ; Vari = (static_cast<double>(Vari) * 10) / 10; cout << endl << "Vari = " << Vari; The cast operator creates a temporary variable of type double with the same value, which is multiplied by 10. Since the type is double, the result fits. Then the result is divided by 10 and assigned to normal Vari. 5/9/2018 Assoc. Prof. Stoyan Bonev
15
Assoc. Prof. Stoyan Bonev
Static casts - example void main() { int intVar = ; //1,500,000,000 intVar = (intVar * 10) / 10; //result too large cout << “intVar = “ << intVar << endl; //wrong answer intVar = ; //cast to double intVar = (static_cast<double>(intVar) * 10) / 10; cout << “intVar = “ << intVar << endl; //right answer } When we multiply the variable intVar by 10, the result—15,000,000,000—is far too large to fit in a variable of type int or unsigned int. This leads to the wrong answer, as shown by the output of the first part of the program. We could redefine the data type of the variables to be double; this provides plenty of room, since this type holds numbers with up to 15 digits. But suppose that for some reason, such as keeping the program small, we don’t want to change the variables to type double. In this case there’s another solution: We can cast intVar to type double before multiplying. This is sometimes called coercion; the data is coerced into becoming another type. The expression static_cast<double>(intVar) casts intVar to type double. It generates a temporary variable of type double with the same value as intVar. It is this temporary variable that is multiplied by 10. Since it is type double, the result fits. This result is then divided by 10 and assigned to the normal int variable intVar. Here’s the program’s output: intVar = intVar = 5/9/2018 Assoc. Prof. Stoyan Bonev
16
Assoc. Prof. Stoyan Bonev
Static casts Static casting is sometimes called coercion. The data is coerced into becoming another type. Example: An integer variable intvar can cast to double type before processing static_cast<double>(intvar) 5/9/2018 Assoc. Prof. Stoyan Bonev
17
Assoc. Prof. Stoyan Bonev
Static casts Demo program:oop5StaticCast.cpp The first result without the cast is wrong. In the second answer, the cast produces the correct result. 5/9/2018 Assoc. Prof. Stoyan Bonev
18
Assoc. Prof. Stoyan Bonev
Static casts Before Standard C++, casts were handled using format like this: vari = (int)varf; vari = int(varf); One problem with these approaches is that they are hard to see and hard to search using text editor vari = static_cast<int>(varf); The new format is easy to see and search. The old casts still work, but their use is discouraged. 5/9/2018 Assoc. Prof. Stoyan Bonev
19
Assoc. Prof. Stoyan Bonev
Static casts Casts should be used when absolutely necessary. They are a controlled way of evading type safety (which means making sure that variables don’t change types by mistake) and can lead to trouble because they make it impossible for the compiler to spot potential problems (Lafore, p60). 5/9/2018 Assoc. Prof. Stoyan Bonev
20
Dynamic casts .
21
Checking the type of a Class
Suppose another program sends your program an object. It’s supposed to be a certain type, but you have to check it. Dynamic_cast provides a way of checking, assuming that the classes whose objects you want to check are all descended from a common ancestor. 5/9/2018 Assoc. Prof. Stoyan Bonev
22
Reinterpret casts .
23
Assoc. Prof. Stoyan Bonev
Reinterpret casts The reinterpret cast operator is how you tell the compiler: “I know you won’t like this, but I want to do it anyway”. It changes the type of a section of memory without care whether it makes sense, so it’s up to you to use it in a reasonable way. 5/9/2018 Assoc. Prof. Stoyan Bonev
24
Const casts .
25
Assoc. Prof. Stoyan Bonev
Const casts No info 5/9/2018 Assoc. Prof. Stoyan Bonev
26
Generic Programming
27
Assoc. Prof. Stoyan Bonev
Lecture Contents: The C++ template reserved word Generic functions Generic classes Examples Generic programming in Java 5/9/2018 Assoc. Prof. Stoyan Bonev
28
Assoc. Prof. Stoyan Bonev
Software Reusability One way to achieve software reusability is to lessen the need to create different subprograms that implement the same algorithm on different types of data. For example, no need to write 4 different routines to sort 4 arrays that differ only in element data type. 5/9/2018 Assoc. Prof. Stoyan Bonev
29
Assoc. Prof. Stoyan Bonev
Generic programming generics is a technique that allows one value to take different datatypes (so-called polymorphism). The programming style emphasizing use of this technique is called generic programming. For example, if one wanted to create a list using generics, a possible declaration would be to say List<T>, where T represented the type. When instantiated, one could create List<Integer> or List<Animal>, or List<Fruit>. The list is then treated as a list of whichever type is specified. 5/9/2018 Assoc. Prof. Stoyan Bonev
30
Assoc. Prof. Stoyan Bonev
Generic programming Traditional class declaration: class List { … }; Traditional class instantiation: List a, b[10], *ptr; Possible class declaration using generics: class List<T> { }; where T is a parameter to represent the type. Class instantiation using generics: List<Integer> l1; List<Animal> l2; List treated as a list of whichever type is specified. 5/9/2018 Assoc. Prof. Stoyan Bonev
31
Software Reusability - terms
A generic or polymorphic subprogram takes parameters of different types on different activations. Overloaded subprograms provide a particular kind of polymorphism, static or ad-hoc polymorphism. Parametric polymorphism is provided by a subprogram that takes a generic parameter that is used in a type expression that describes the types of the parameters of the subprogram. C++ provides a compile-time parametric polymorphism, based on template reserved word. 5/9/2018 Assoc. Prof. Stoyan Bonev
32
Generic Functions in C++
33
Generic functions in C++
A generic or polymorphic subprogram takes parameters of different types on different activations. Generic functions in C++ are known as template functions. The definition of a generic function is based on the template reserved word. It has the following general form: 5/9/2018 Assoc. Prof. Stoyan Bonev
34
Generic functions in C++
General form of a generic function definition: template <class parameters> followed by a function definition that may include the class parameters Class parameter form (there must be at least one): class identifier {,class identifier}* 5/9/2018 Assoc. Prof. Stoyan Bonev
35
Assoc. Prof. Stoyan Bonev
Task: to implement function max(oprnd1, oprnd2) for all 4 basic data types Solution 1: 4 separate functions char max1(char, char); int max2(int, int); float max3(float, float); double max4(double, double); 5/9/2018 Assoc. Prof. Stoyan Bonev
36
Assoc. Prof. Stoyan Bonev
Task: to implement function max(oprnd1, oprnd2) for all 4 basic data types Solution 2a: Overloaded functions char max(char, char); int max(int, int); float max(float, float); double max(double, double); 5/9/2018 Assoc. Prof. Stoyan Bonev
37
Assoc. Prof. Stoyan Bonev
Task: to implement function max(oprnd1, oprnd2) for all 4 basic data types Solution 2b: Overloaded functions void max(char, char, char&); void max(int, int, int&); void max(float, float, float&); void max(double, double, double&); 5/9/2018 Assoc. Prof. Stoyan Bonev
38
Assoc. Prof. Stoyan Bonev
Task: to implement function max(oprnd1, oprnd2) for all 4 basic data types Solution 3: Generic, parametric function template <class T> T max(T& oprnd1, T& oprnd2) { if (oprnd1 > oprnd2) return oprnd1; else return oprnd2; } Demo program oop5aGenericFunctions.cpp 5/9/2018 Assoc. Prof. Stoyan Bonev
39
Assoc. Prof. Stoyan Bonev
Demo program oop5a.cpp template <class TYPE> TYPE max(TYPE& x, TYPE& y) { return (x>y) ? x : y ; } TYPE min(TYPE& x, TYPE& y) return (x<y) ? x : y ; 5/9/2018 Assoc. Prof. Stoyan Bonev
40
Assoc. Prof. Stoyan Bonev
Demo program oop5a.cpp void main() { int a=20, b=50; cout << "\n\na="<<a<<" b="<<b<<" max(a,b)="<<max(a,b)<<" min(a,b)="<<min(a,b); float c=4.5f, d=6.8f; cout << "\n\nc="<<c<<" d="<<d<<" max(c,d)="<<max(c,d)<<" min(c,d)="<<min(c,d); double e=44.55, f=66.88; cout << "\n\ne="<<e<<" f="<<f<<" max(e,f)="<<max(e,f)<<" min(e,f)="<<min(e,f); char g='a', h='b'; cout << "\n\ng="<<g<<“ h="<<h<<" max(g,h)="<<max(g,h)<<" min(g,h)="<<min(g,h); } 5/9/2018 Assoc. Prof. Stoyan Bonev
41
Generic Classes in C++
42
Assoc. Prof. Stoyan Bonev
Generic Classes in C++ It is convenient to parameterize abstract data types. It is better to design a stack user defined type that can store any scalar type elements rather than be required to write a stack abstraction for every different scalar type. The definition of a generic class is based on the template reserved word. 5/9/2018 Assoc. Prof. Stoyan Bonev
43
Assoc. Prof. Stoyan Bonev
Generic Classes in C++ General form of a generic class definition: template <class parameters> followed by a class definition that may include the class parameters Class parameters form (there must be at least one): class identifier 5/9/2018 Assoc. Prof. Stoyan Bonev
44
Assoc. Prof. Stoyan Bonev
Task: to implement 4 classes with the same structure that differ by the type of a data component class X1{ private: char item; public: X1() { item = 0;} X1(char p) { item = p; } char getItem() { return item; } void setItem(char p) { item = p; } }; . . . X1 obj1; obj1.setItem(‘E’); cout << obj1.getItem(); 5/9/2018 Assoc. Prof. Stoyan Bonev
45
Assoc. Prof. Stoyan Bonev
Task: to implement 4 classes with the same structure that differ by the type of a data component class X2{ private: int item; public: X2() { item = 0;} X2(int p) { item = p; } int getItem() { return item; } void setItem(int p) { item = p; } }; . . . X2 obj2; obj2.setItem(715); cout << obj2.getItem(); 5/9/2018 Assoc. Prof. Stoyan Bonev 45
46
Assoc. Prof. Stoyan Bonev
Task: to implement 4 classes with the same structure that differ by the type of a data component class X3{ private: float item; public: X3() { item = 0.0F;} X3(float p) { item = p; } float getItem() { return item; } void setItem(float p) { item = p; } }; . . . X3 obj3; obj3.setItem(3.14f); cout << obj3.getItem(); 5/9/2018 Assoc. Prof. Stoyan Bonev 46
47
Assoc. Prof. Stoyan Bonev
Task: to implement 4 classes with the same structure that differ by the type of a data component class X4{ private: double item; public: X4() { item = 0.0;} X4(double p) { item = p; } double getItem() { return item; } void setItem(double p) { item = p; } }; . . . X4 obj4; obj4.setItem(2.78); cout << obj4.getItem(); 5/9/2018 Assoc. Prof. Stoyan Bonev 47
48
The solution: generic class definition
template <class Type > class X { private: Type item; public: X() { item = 0;} X(Type p) { item = p; } Type getItem() { return item; } void setItem(Type p) { item = p; } }; 5/9/2018 Assoc. Prof. Stoyan Bonev
49
The solution: generic class definition
. . . X<char> obj1; X<int> obj2; X<float> obj3; X<double> obj4; 5/9/2018 Assoc. Prof. Stoyan Bonev
50
Assoc. Prof. Stoyan Bonev
Demo program oop5b.cpp Generic stack class definition template <class TYPE, int SIZE> class Stack { public: Stack() { . . .} void push(TYPE var) { } TYPE pop() { } private: TYPE st[SIZE]; int sp; }; . . . Stack<int, 100> c1; Stack<float, 200> c2; 5/9/2018 Assoc. Prof. Stoyan Bonev
51
Assoc. Prof. Stoyan Bonev
Demo Program file:oop5bGenericClassStack.cpp 5/9/2018 Assoc. Prof. Stoyan Bonev
52
Assoc. Prof. Stoyan Bonev
Demo program oop5b.cpp template <class TYPE, int SIZE> class Stack { private: TYPE st[SIZE]; int sp; public: Stack() { sp = -1; } // constructor void push(TYPE var) { if (sp < SIZE-1) { sp++; st[sp] = var; } else { cout << "\n Stack full\n"; getch(); exit(1); } } TYPE pop() { TYPE pom; if (sp>=0) { pom = st[sp]; sp--; return pom; } else { cout << "\n Stack empty\n"; getch(); exit(2); } ~Stack() { cout << endl << "GOOD Bye"; } // Destructor }; 5/9/2018 Assoc. Prof. Stoyan Bonev
53
Assoc. Prof. Stoyan Bonev
Demo program oop5b.cpp main() { Stack<int, 100> c1; c1.push(22); c1.push(33); cout << c1.pop(); Stack<float, 10> M; M.push(11.2); M.push(22.4); M.push(33.6); M.push(44.8); M.push(55.9); M.push(66.6); cout << "\n\nStack contents" << endl; cout << M.pop() << endl; cout << M.pop() << endl; cout << M.pop() << endl; char ch; cin>> ch; } 5/9/2018 Assoc. Prof. Stoyan Bonev
54
Templates (advantages/disadvantages)
Some uses of templates, such as the max() function, are similar to preprocessor macros. For example, here is a max() macro: #define max(a,b) ((a) < (b) ? (b) : (a)) Both macros and templates are expanded at compile time. Macros are always expanded inline; templates can also be expanded as inline functions when the compiler deems it appropriate. Thus both function-like macros and function templates have no run-time overhead. However, templates are generally considered an improvement over macros for these purposes: Templates are type-safe Templates avoid some of the common errors found in code that makes heavy use of function-like macros. Templates were designed to be applicable to much larger problems than macros. 5/9/2018 Assoc. Prof. Stoyan Bonev
55
Templates (advantages/disadvantages)
There are three primary drawbacks to the use of templates: First, many compilers historically have very poor support for templates, so the use of templates can make code somewhat less portable. Second, almost all compilers produce confusing, unhelpful error messages when errors are detected in template code. This can make templates difficult to develop. Third, each use of a template may cause the compiler to generate extra code (an instantiation of the template), so the indiscriminate use of templates can lead to code bloat, resulting in excessively large executables. The extra instantiations generated by templates can also cause debuggers to have difficulty working gracefully with templates. For example, setting a debug breakpoint within a template from a source file may either miss setting the breakpoint in the actual instantiation desired or may set a breakpoint in every place the template is instantiated. 5/9/2018 Assoc. Prof. Stoyan Bonev
56
Polymorphism in C++ classified
Parametric (generic) polymorphism Based oh template reserved word Static or ad-hoc polymorphism Based on overloaded functions concept Dynamic polymorphism Based on late binding and virtual methods 5/9/2018 Assoc. Prof. Stoyan Bonev
57
Assoc. Prof. Stoyan Bonev
Generic programming in Java What about Java? Java doesn't have a generic (or template) mechanism. Instead it is suggested that containers can hold values of type Object, and since every type is by definition a sub-type of Object then by the rules of sub-typing the container can hold values of any type 5/9/2018 Assoc. Prof. Stoyan Bonev
58
Generic programming in Java
class Stack { protected Object mem[]; protected int sp; public Stack() { mem = new Object[100]; sp=-1; } public boolean empty() { return sp<0; } public boolean full() { return 99==sp; } public Object top() {if(empty()) return null; else return mem[sp];} public void pop() { if(! empty()) sp=sp-1; } public void push(Object s) { if(! full()) { sp=sp+1; mem[sp]=s; } } } 5/9/2018 Assoc. Prof. Stoyan Bonev
59
Generic programming in Java
public class StackUse { public static void main(String args[]) { Stack filo = new Stack(); int sum = 0; filo.push(new Integer(22)); filo.push(new Integer(33)); filo.push("should be a number"); filo.push(new Integer(55)); System.out.println("Pop contents and add them up"); while( !filo.empty() ) {sum = sum + ((Integer)filo.top()).intValue(); filo.pop();} System.out.println("sum = " + sum); } 5/9/2018 Assoc. Prof. Stoyan Bonev
60
Generic programming in Java
Here the Stack filo objects can contain any type descended from Object, that includes everything except the primitive types int, char etc. In the program above it is not possible to have: filo.push(33), the int must be wrapped in an Integer object: filo.push(new Integer(33)). When the values are popped off the stack they are only Objects (which don't all have an integer value) so they must be ``cast'' to Integer and then the int can be retrieved: sum = sum + ((Integer)filo.top()).intValue(); 5/9/2018 Assoc. Prof. Stoyan Bonev
61
Generic programming in Java
However since everything is an Object, other stuff, like the String above, can be accidentally pushed on the stack with no static compile time type error. This is OK until the string is popped off and cast to an Integer, which it clearly isn't. It causes a runtime type error: rabbit(340)$ java StackUse Pop contents and add them up java.lang.ClassCastException: at StackUse.main(StackUse.java:27) 5/9/2018 Assoc. Prof. Stoyan Bonev
62
Exercise OOP. Parameterized Abstract (User Defined) Data Types
Test all programs (generic functions and generic classes) discussed in the lecture. Build own programs to illustrate the utilization and application of generic functions and generic classes. Assignments under discussion are based on lecture 25. 5/9/2018 Assoc. Prof. Stoyan Bonev
63
Assoc. Prof. Stoyan Bonev
Tasks Task1. Build a generic template function to return the location of a particular value in an array of any type (int, float, …) based on the linear search algorithm. Demo program OOP5RecursiveIterativeLinBinSearch.cpp 5/9/2018 Assoc. Prof. Stoyan Bonev
64
Assoc. Prof. Stoyan Bonev
Tasks Task2. Build a generic template function to return the location of a particular value in an array of any type (int, float, …) based on the binary search algorithm. Demo program OOP5RecursiveIterativeLinBinSearch.cpp 5/9/2018 Assoc. Prof. Stoyan Bonev
65
Assoc. Prof. Stoyan Bonev
Tasks Task 3. Build a generic class simulating the Queue data structure (methods put(), get(), peekLeft(), peekRight() ) permitting to vary with data types of the queue as well as the size of the queue. Sample definition: Queue <int, 100> q1; Queue <float, 120> q2; 5/9/2018 Assoc. Prof. Stoyan Bonev
66
Assoc. Prof. Stoyan Bonev
Tasks Task 4. Build a generic class simulating the double ended queue data structure (methods putLeft(), putRight(), getLeft(), getRight(), peekLeft(), peekRight() ) permitting to vary with data types of the dequeue as well as the size of the dequeue. Sample definition: Deque <int, 100> deq1; Deque <double, 70> deq2; 5/9/2018 Assoc. Prof. Stoyan Bonev
67
Assoc. Prof. Stoyan Bonev
Tasks Task 5. Build a generic class simulating the list data structure (methods add(), detach(), peekHead() ) permitting to vary with data types of the list as well as the size of the list. Sample definition: List <int, 100> list1; List <char *, 18> list2; 5/9/2018 Assoc. Prof. Stoyan Bonev
68
Chapter 9 Subprograms Source: Longman dictionary 1987 68
69
Generic Subprograms A generic or polymorphic subprogram takes parameters of different types on different activations Overloaded subprograms provide ad hoc polymorphism A subprogram that takes a generic parameter that is used in a type expression that describes the type of the parameters of the subprogram provides parametric polymorphism - A cheap compile-time substitute for dynamic binding Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-69 Source: Longman dictionary 1987 69
70
Generic Subprograms (continued)
Ada Versions of a generic subprogram are created by the compiler when explicitly instantiated by a declaration statement Generic subprograms are preceded by a generic clause that lists the generic variables, which can be types or other subprograms Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-70
71
Generic Subprograms (continued)
Versions of a generic subprogram are created implicitly when the subprogram is named in a call or when its address is taken with the & operator Generic subprograms are preceded by a template clause that lists the generic variables, which can be type names or class names Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-71
72
Generic Subprograms (continued)
Java Differences between generics in Java 5.0 and those of C++ and Ada: 1. Generic parameters in Java 5.0 must be classes 2. Java 5.0 generic methods are instantiated just once as truly generic methods 3. Restrictions can be specified on the range of classes that can be passed to the generic method as generic parameters 4. Wildcard types of generic parameters Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-72 Source: Longman dictionary 1987 72
73
Generic Subprograms (continued)
C# Supports generic methods that are similar to those of Java One difference: actual type parameters in a call can be omitted if the compiler can infer the unspecified type Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-73 Source: Longman dictionary 1987 73
74
Examples of parametric polymorphism: C++
template <class Type> Type max(Type first, Type second) { return first > second ? first : second; } The above template can be instantiated for any type for which operator > is defined int max (int first, int second) { return first > second? first : second; Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-74 Source: Longman dictionary 1987 74
75
Abstract Data Types and Encapsulation Concepts
Chapter 11 Abstract Data Types and Encapsulation Concepts Source: Longman dictionary 1987 75
76
Parameterized Abstract Data Types
Parameterized ADTs allow designing an ADT that can store any type elements (among other things) – only an issue for static typed languages Also known as generic classes C++, Ada, Java 5.0, and C# 2005 provide support for parameterized ADTs Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-76 Source: Longman dictionary 1987 76
77
Parameterized ADTs in Ada
Ada Generic Packages Make the stack type more flexible by making the element type and the size of the stack generic generic Max_Size: Positive; type Elem_Type is private; package Generic_Stack is Type Stack_Type is limited private; function Top(Stk: in out StackType) return Elem_type; … end Generic_Stack; Package Integer_Stack is new Generic_Stack(100,Integer); Package Float_Stack is new Generic_Stack(100,Float); Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-77 Source: Longman dictionary 1987 77
78
Parameterized ADTs in C++
Classes can be somewhat generic by writing parameterized constructor functions class Stack { … Stack (int size) { stk_ptr = new int [size]; max_len = size - 1; top = -1; }; } Stack stk(100); Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-78 Source: Longman dictionary 1987 78
79
Parameterized ADTs in C++ (continued)
The stack element type can be parameterized by making the class a templated class template <class Type> class Stack { private: Type *stackPtr; const int maxLen; int topPtr; public: Stack() { stackPtr = new Type[100]; maxLen = 99; topPtr = -1; } … } Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-79 Source: Longman dictionary 1987 79
80
Parameterized Classes in Java 5.0
Generic parameters must be classes Most common generic types are the collection types, such as LinkedList and ArrayList Eliminate the need to cast objects that are removed Eliminate the problem of having multiple types in a structure Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-80 Source: Longman dictionary 1987 80
81
Parameterized Classes in C# 2005
Similar to those of Java 5.0 Elements of parameterized structures can be accessed through indexing Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-81 Source: Longman dictionary 1987 81
82
Thank You For Your Attention
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.