SlideShare a Scribd company logo
1 of 16
Download to read offline
1
Templates and Polymorphism
Generic functions and classes
JPC and JWD © 2002 McGraw-Hill, Inc.
Polymorphic Functions
What are they?
Generic functions that can act upon objects of different
types
The action taken depends upon the types of the objects
Where have we seen them beforeWhere have we seen them before?
Function overloading
Define functions or operators with the same name
Rational addition operator +
Function Min() for the various numeric types
Primitive polymorphism
2
Polymorphic Functions
Templates
Generate a function or class at compile time
Where have we seen them before?
Templates
Generate a function or class at compile time
Where have we seen them before?
Standard Template Library
Vector and other container classes
Templates
Generate a function or class at compile time
Where have we seen them before?
Standard Template Library
Vector and other container classes
True polymorphism
Choice of which function to execute is made during run time
C++ uses virtual functions
Templates
Generate a function or class at compile time
Function Templates
Current scenario
We rewrite functions Min(), Max(), and InsertionSort() for
many different types
There has to be a better way
Function template
Describes a function format that when instantiated with
particulars generates a function definition
Write once, use multiple times
3
An Example Function Template
template <class T>
T Min(const T &a, const T &b) {
if (a < b)
return a;
else
return b;
}
Indicates a template is being defined
Indicates T is our formal template
parameter
Instantiated functions
will return a value
whose type is the
actual template
parameter
Instantiated functions
require two actual
parameters of the
same type. Their
type will be the
actual value for T
Min Template
Code segment
int Input1 = PromptAndRead();
int Input2 = PromptAndRead();
cout << Min(Input1, Input2) << endl;
Causes the following function to be generated from our
template
int Min(const int &a, const int &b) {
if (a < b)
return a;
else
return b;
}
4
Min Template
Code segment
double Value1 = 4.30;
double Value2 = 19.54;
cout << Min(Value1, Value2) << endl;
Causes the following function to be generated from our
template
double Min(const double &a, const double &b) {
if (a < b)
return a;
else
return b;
}
Min Template
Code segment
Rational r(6,21);
Rational s(11,29);
cout << Min(r, s) << endl;
Causes the following function to be generated from our template
Rational Min(const Rational &a, const Rational &b){
if (a < b)
return a;
else
return b;
}
Operator < needs to be defined for
for the actual template parameter
type. If < is not defined, then a
compile-time error occurs
5
Function Templates Facts
Location in program files
In current compilers
Template definitions are part of header files
Possible template instantiation failure scenario
cout << min(7, 3.14); // different parameter
// types
Generic Sorting
template <class T>
void InsertionSort(T A[], int n) {
for (int i = 1; i < n; ++i) {
if (A[i] < A[i-1]) {
T val = A[i];
int j = i;
do { A[j] = A[j-1];
--j;
} while ((j > 0) && (val < A[j-1]));
A[j] = val;
}
}
}
6
STL’s Template Functions
STL provides template definitions for many programming tasks
Use them! Do not reinvent the wheel!
STL provides template definitions for many programming tasks
Use them! Do not reinvent the wheel!
Searching and sorting
find(), find_if(), count(), count_if(),
min(), max(), binary_search(),
lower_bound(), upper_bound(), sort()
STL provides template definitions for many programming tasks
Use them! Do not reinvent the wheel!
Searching and sorting
find(), find_if(), count(), count_if(),
min(), max(), binary_search(),
lower_bound(), upper_bound(), sort()
Comparing
equal()
STL provides template definitions for many programming tasks
Use them! Do not reinvent the wheel!
Searching and sorting
find(), find_if(), count(), count_if(),
min(), max(), binary_search(),
lower_bound(), upper_bound(), sort()
Comparing
equal()
Rearranging and copying
unique(), replace(), copy(), remove(),
reverse(), random_shuffle(), merge()
STL provides template definitions for many programming tasks
Use them! Do not reinvent the wheel!
Searching and sorting
find(), find_if(), count(), count_if(),
min(), max(), binary_search(),
lower_bound(), upper_bound(), sort()
Comparing
equal()
Rearranging and copying
unique(), replace(), copy(), remove(),
reverse(), random_shuffle(), merge()
Iterating
for_each()
Class Templates
Rules
Type template parameters
Value template parameters
Place holder for a value
Described using a known type and an identifier name
Template parameters must be used in class definition
described by template
Implementation of member functions in header file
Compilers require it for now
7
A Generic Array Representation
We will develop a class Array
Template version of IntList
Provides additional insight into container classes of STL
Homegrown Generic Arrays
Array<int> A(5, 0); // A is five 0's
const Array<int> B(6, 1); // B is six 1's
Array<Rational> C; // C is ten 0/1's
A = B;
A[5] = 3;
A[B[1]] = 2;
cout << "A = " << A << endl; // [ 1 2 1 1 1 3
]
cout << "B = " << B << endl; // [ 1 1 1 1 1 1
]
cout << "C = " << D << endl;
// [ 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1
]
8
template <class T>
class Array {
public:
Array(int n = 10, const T &val = T());
Array(const T A[], int n);
Array(const Array<T> &A);
~Array();
int size() const {
return NumberValues;
}
Array<T> & operator=(const Array<T> &A);
const T& operator[](int i) const;
T& operator[](int i);
private:
int NumberValues;
T *Values;
};
Optional value is default constructed
Inlined function
Auxiliary Operators
template <class T>
ostream& operator<<
(ostream &sout, const Array<T> &A);
template <class T>
istream& operator>>
(istream &sin, Array<T> &A);
9
Default Constructor
template <class T>
Array<T>::Array(int n, const T &val) {
assert(n > 0);
NumberValues = n;
Values = new T [n];
assert(Values);
for (int i = 0; i < n’ ++ i) {
Values[i] = A[i];
}
}
Copy Constructor
template <class T>
Array<T>::Array(const Array<T> &A) {
NumberValues = A.size();
Values = new T [A.size()];
assert(Values);
for (int i = 0; i < A.size(); ++i) {
Values[i] = A[i];
}
}
10
Destructor
template <class T>
Array<T>::~Array() {
delete [] Values;
}
Member Assignment
template <class T>
Array<T>& Array<T>::operator=(const Array<T> &A) {
if ( this != &A ) {
if (size() != A.size()) {
delete [] Values;
NumberValues = A.size();
Values = new T [A.size()];
assert(Values);
}
for (int i = 0; i < A.size(); ++i) {
Values[i] = A[i];
}
}
return *this;
}
11
Inspector for Constant Arrays
template <class T>
const T& Array<T>::operator[](int i) const {
assert((i >= 0) && (i < size()));
return Values[i];
}
Nonconstant Inspector/Mutator
template <class T>
T& Array<T>::operator[](int i) {
assert((i >= 0) && (i < size()));
return Values[i];
}
12
Generic Array Insertion Operator
template <class T>
ostream& operator<<(ostream &sout,
const Array<T> &A){
sout << "[ ";
for (int i = 0; i < A.size(); ++i) {
sout << A[i] << " ";
}
sout << "]";
return sout;
}
Can be instantiated for whatever type of Array we need
Specific Array Insertion Operator
Suppose we want a different Array insertion operator for
Array<char> objects
ostream& operator<<(ostream &sout,
const Array<char> &A){
for (int i = 0; i < A.size(); ++i) {
sout << A[i];
}
return sout;
}
13
Scenario
Manipulate list of heterogeneous objects with common base class
Example: a list of graphical shapes to be drawn
// what we would like
for (int i = 0; i < n; ++i) {
A[i].Draw();
}
Manipulate list of heterogeneous objects with common base class
Example: a list of graphical shapes to be drawn
// what we would like
for (int i = 0; i < n; ++i) {
A[i].Draw();
}
Need
Draw() to be a virtual function
Placeholder in the Shape class with specialized
definitions in the derived class
In C++ we can come close
Virtual Functions
For virtual functions
It is the type of object to which the pointer refers that
determines which function is invoked
TriangleShape T(W, P, Red, 1);
RectangleShape R(W,P, Yellow, 3, 2);
CircleShape C(W, P, Yellow, 4);
Shape *A[3] = {&T, &R, &C};
for (int i = 0; i < 3; ++i) {
A[i]->Draw();
} When i is 0, a TriangleShape’s
Draw() is used
14
Virtual Functions
For virtual functions
It is the type of object to which the pointer refers that
determines which function is invoked
TriangleShape T(W, P, Red, 1);
RectangleShape R(W,P, Yellow, 3, 2);
CircleShape C(W, P, Yellow, 4);
Shape *A[3] = {&T, &R, &C};
for (int i = 0; i < 3; ++i) {
A[i]->Draw();
} When i is 1, a RectangleShape’s
Draw() is used
Virtual Functions
For virtual functions
It is the type of object to which the pointer refers that
determines which function is invoked
TriangleShape T(W, P, Red, 1);
RectangleShape R(W,P, Yellow, 3, 2);
CircleShape C(W, P, Yellow, 4);
Shape *A[3] = {&T, &R, &C};
for (int i = 0; i < 3; ++i) {
A[i]->Draw();
} When i is 2, a CircleShape’s
Draw() is used
15
A Shape Class with a Virtual Draw
class Shape : public WindowObject {
public:
Shape(SimpleWindow &w, const Position &p,
const color c = Red);
color GetColor() const;
void SetColor(const color c);
virtual void Draw(); // virtual function!
private:
color Color;
};
Virtual Functions
Can be invoked via either a dereferenced pointer or a reference
object
Actual function to be invoked is determined from the type of
object that is stored at the memory location being accessed
Can be invoked via either a dereferenced pointer or a reference
object
Actual function to be invoked is determined from the type of
object that is stored at the memory location being accessed
Definition of the derived function overrides the definition of the
base class version
Can be invoked via either a dereferenced pointer or a reference
object
Actual function to be invoked is determined from the type of
object that is stored at the memory location being accessed
Definition of the derived function overrides the definition of the
base class version
Determination of which virtual function to use cannot always be
made at compile time
Decision is deferred by the compiler to run time
Introduces overhead
16
Pure Virtual Function
Has no implementationHas no implementation
A pure virtual function is specified in C++ by assigning the
function the null address within its class definition
Has no implementation
A pure virtual function is specified in C++ by assigning the
function the null address within its class definition
A class with a pure virtual function is an abstract base class
Convenient for defining interfaces
Base class cannot be directly instantiated
A Shape Abstract Base Class
class Shape : public WindowObject {
public:
Shape(SimpleWindow &w, const Position &p,
const color &c = Red);
color GetColor() const;
void SetColor(const color &c);
virtual void Draw() = 0; // pure virtual
// function!
private:
color Color;
};

More Related Content

What's hot

Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testingScott Wlaschin
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2YOGESH SINGH
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2Chris Huang
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1Chris Huang
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 

What's hot (20)

Java operators
Java operatorsJava operators
Java operators
 
pointers
pointerspointers
pointers
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Arrays
ArraysArrays
Arrays
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Arrays
ArraysArrays
Arrays
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1
 
Pointer
PointerPointer
Pointer
 
Scala functions
Scala functionsScala functions
Scala functions
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Templates
TemplatesTemplates
Templates
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 

Similar to Bw14

Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notesGOKULKANNANMMECLECTC
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it outrajatryadav22
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariTHE NORTHCAP UNIVERSITY
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxSirRafiLectures
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMSfawzmasood
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of cTushar B Kute
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?Amir Barylko
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 

Similar to Bw14 (20)

CP 04.pptx
CP 04.pptxCP 04.pptx
CP 04.pptx
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan Kumari
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
The STL
The STLThe STL
The STL
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 

Recently uploaded

Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...anamikaraghav4
 
2k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 92055419142k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 9205541914Delhi Call girls
 
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...noor ahmed
 
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...ranjana rawat
 
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...rahim quresi
 
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...Apsara Of India
 
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...ritikasharma
 
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...anamikaraghav4
 
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...anamikaraghav4
 
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near MeBook Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Meanamikaraghav4
 
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Low Rate Call Girls Ajmer Anika 8250192130 Independent Escort Service Ajmer
Low Rate Call Girls Ajmer Anika 8250192130 Independent Escort Service AjmerLow Rate Call Girls Ajmer Anika 8250192130 Independent Escort Service Ajmer
Low Rate Call Girls Ajmer Anika 8250192130 Independent Escort Service AjmerRiya Pathan
 
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur EscortsVIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Jinx Manga-Season 1 - Chapters Summary.docx
Jinx Manga-Season 1 - Chapters Summary.docxJinx Manga-Season 1 - Chapters Summary.docx
Jinx Manga-Season 1 - Chapters Summary.docxJinx Manga
 
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment BookingCall Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Bookingnoor ahmed
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Recently uploaded (20)

Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
 
2k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 92055419142k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 9205541914
 
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
 
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
 
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
 
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
 
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
 
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
 
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
 
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
 
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near MeBook Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
 
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
 
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
 
Low Rate Call Girls Ajmer Anika 8250192130 Independent Escort Service Ajmer
Low Rate Call Girls Ajmer Anika 8250192130 Independent Escort Service AjmerLow Rate Call Girls Ajmer Anika 8250192130 Independent Escort Service Ajmer
Low Rate Call Girls Ajmer Anika 8250192130 Independent Escort Service Ajmer
 
Call Girls South Avenue Delhi WhatsApp Number 9711199171
Call Girls South Avenue Delhi WhatsApp Number 9711199171Call Girls South Avenue Delhi WhatsApp Number 9711199171
Call Girls South Avenue Delhi WhatsApp Number 9711199171
 
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur EscortsVIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
 
Jinx Manga-Season 1 - Chapters Summary.docx
Jinx Manga-Season 1 - Chapters Summary.docxJinx Manga-Season 1 - Chapters Summary.docx
Jinx Manga-Season 1 - Chapters Summary.docx
 
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
 
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment BookingCall Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
 

Bw14

  • 1. 1 Templates and Polymorphism Generic functions and classes JPC and JWD © 2002 McGraw-Hill, Inc. Polymorphic Functions What are they? Generic functions that can act upon objects of different types The action taken depends upon the types of the objects Where have we seen them beforeWhere have we seen them before? Function overloading Define functions or operators with the same name Rational addition operator + Function Min() for the various numeric types Primitive polymorphism
  • 2. 2 Polymorphic Functions Templates Generate a function or class at compile time Where have we seen them before? Templates Generate a function or class at compile time Where have we seen them before? Standard Template Library Vector and other container classes Templates Generate a function or class at compile time Where have we seen them before? Standard Template Library Vector and other container classes True polymorphism Choice of which function to execute is made during run time C++ uses virtual functions Templates Generate a function or class at compile time Function Templates Current scenario We rewrite functions Min(), Max(), and InsertionSort() for many different types There has to be a better way Function template Describes a function format that when instantiated with particulars generates a function definition Write once, use multiple times
  • 3. 3 An Example Function Template template <class T> T Min(const T &a, const T &b) { if (a < b) return a; else return b; } Indicates a template is being defined Indicates T is our formal template parameter Instantiated functions will return a value whose type is the actual template parameter Instantiated functions require two actual parameters of the same type. Their type will be the actual value for T Min Template Code segment int Input1 = PromptAndRead(); int Input2 = PromptAndRead(); cout << Min(Input1, Input2) << endl; Causes the following function to be generated from our template int Min(const int &a, const int &b) { if (a < b) return a; else return b; }
  • 4. 4 Min Template Code segment double Value1 = 4.30; double Value2 = 19.54; cout << Min(Value1, Value2) << endl; Causes the following function to be generated from our template double Min(const double &a, const double &b) { if (a < b) return a; else return b; } Min Template Code segment Rational r(6,21); Rational s(11,29); cout << Min(r, s) << endl; Causes the following function to be generated from our template Rational Min(const Rational &a, const Rational &b){ if (a < b) return a; else return b; } Operator < needs to be defined for for the actual template parameter type. If < is not defined, then a compile-time error occurs
  • 5. 5 Function Templates Facts Location in program files In current compilers Template definitions are part of header files Possible template instantiation failure scenario cout << min(7, 3.14); // different parameter // types Generic Sorting template <class T> void InsertionSort(T A[], int n) { for (int i = 1; i < n; ++i) { if (A[i] < A[i-1]) { T val = A[i]; int j = i; do { A[j] = A[j-1]; --j; } while ((j > 0) && (val < A[j-1])); A[j] = val; } } }
  • 6. 6 STL’s Template Functions STL provides template definitions for many programming tasks Use them! Do not reinvent the wheel! STL provides template definitions for many programming tasks Use them! Do not reinvent the wheel! Searching and sorting find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort() STL provides template definitions for many programming tasks Use them! Do not reinvent the wheel! Searching and sorting find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort() Comparing equal() STL provides template definitions for many programming tasks Use them! Do not reinvent the wheel! Searching and sorting find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort() Comparing equal() Rearranging and copying unique(), replace(), copy(), remove(), reverse(), random_shuffle(), merge() STL provides template definitions for many programming tasks Use them! Do not reinvent the wheel! Searching and sorting find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort() Comparing equal() Rearranging and copying unique(), replace(), copy(), remove(), reverse(), random_shuffle(), merge() Iterating for_each() Class Templates Rules Type template parameters Value template parameters Place holder for a value Described using a known type and an identifier name Template parameters must be used in class definition described by template Implementation of member functions in header file Compilers require it for now
  • 7. 7 A Generic Array Representation We will develop a class Array Template version of IntList Provides additional insight into container classes of STL Homegrown Generic Arrays Array<int> A(5, 0); // A is five 0's const Array<int> B(6, 1); // B is six 1's Array<Rational> C; // C is ten 0/1's A = B; A[5] = 3; A[B[1]] = 2; cout << "A = " << A << endl; // [ 1 2 1 1 1 3 ] cout << "B = " << B << endl; // [ 1 1 1 1 1 1 ] cout << "C = " << D << endl; // [ 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 ]
  • 8. 8 template <class T> class Array { public: Array(int n = 10, const T &val = T()); Array(const T A[], int n); Array(const Array<T> &A); ~Array(); int size() const { return NumberValues; } Array<T> & operator=(const Array<T> &A); const T& operator[](int i) const; T& operator[](int i); private: int NumberValues; T *Values; }; Optional value is default constructed Inlined function Auxiliary Operators template <class T> ostream& operator<< (ostream &sout, const Array<T> &A); template <class T> istream& operator>> (istream &sin, Array<T> &A);
  • 9. 9 Default Constructor template <class T> Array<T>::Array(int n, const T &val) { assert(n > 0); NumberValues = n; Values = new T [n]; assert(Values); for (int i = 0; i < n’ ++ i) { Values[i] = A[i]; } } Copy Constructor template <class T> Array<T>::Array(const Array<T> &A) { NumberValues = A.size(); Values = new T [A.size()]; assert(Values); for (int i = 0; i < A.size(); ++i) { Values[i] = A[i]; } }
  • 10. 10 Destructor template <class T> Array<T>::~Array() { delete [] Values; } Member Assignment template <class T> Array<T>& Array<T>::operator=(const Array<T> &A) { if ( this != &A ) { if (size() != A.size()) { delete [] Values; NumberValues = A.size(); Values = new T [A.size()]; assert(Values); } for (int i = 0; i < A.size(); ++i) { Values[i] = A[i]; } } return *this; }
  • 11. 11 Inspector for Constant Arrays template <class T> const T& Array<T>::operator[](int i) const { assert((i >= 0) && (i < size())); return Values[i]; } Nonconstant Inspector/Mutator template <class T> T& Array<T>::operator[](int i) { assert((i >= 0) && (i < size())); return Values[i]; }
  • 12. 12 Generic Array Insertion Operator template <class T> ostream& operator<<(ostream &sout, const Array<T> &A){ sout << "[ "; for (int i = 0; i < A.size(); ++i) { sout << A[i] << " "; } sout << "]"; return sout; } Can be instantiated for whatever type of Array we need Specific Array Insertion Operator Suppose we want a different Array insertion operator for Array<char> objects ostream& operator<<(ostream &sout, const Array<char> &A){ for (int i = 0; i < A.size(); ++i) { sout << A[i]; } return sout; }
  • 13. 13 Scenario Manipulate list of heterogeneous objects with common base class Example: a list of graphical shapes to be drawn // what we would like for (int i = 0; i < n; ++i) { A[i].Draw(); } Manipulate list of heterogeneous objects with common base class Example: a list of graphical shapes to be drawn // what we would like for (int i = 0; i < n; ++i) { A[i].Draw(); } Need Draw() to be a virtual function Placeholder in the Shape class with specialized definitions in the derived class In C++ we can come close Virtual Functions For virtual functions It is the type of object to which the pointer refers that determines which function is invoked TriangleShape T(W, P, Red, 1); RectangleShape R(W,P, Yellow, 3, 2); CircleShape C(W, P, Yellow, 4); Shape *A[3] = {&T, &R, &C}; for (int i = 0; i < 3; ++i) { A[i]->Draw(); } When i is 0, a TriangleShape’s Draw() is used
  • 14. 14 Virtual Functions For virtual functions It is the type of object to which the pointer refers that determines which function is invoked TriangleShape T(W, P, Red, 1); RectangleShape R(W,P, Yellow, 3, 2); CircleShape C(W, P, Yellow, 4); Shape *A[3] = {&T, &R, &C}; for (int i = 0; i < 3; ++i) { A[i]->Draw(); } When i is 1, a RectangleShape’s Draw() is used Virtual Functions For virtual functions It is the type of object to which the pointer refers that determines which function is invoked TriangleShape T(W, P, Red, 1); RectangleShape R(W,P, Yellow, 3, 2); CircleShape C(W, P, Yellow, 4); Shape *A[3] = {&T, &R, &C}; for (int i = 0; i < 3; ++i) { A[i]->Draw(); } When i is 2, a CircleShape’s Draw() is used
  • 15. 15 A Shape Class with a Virtual Draw class Shape : public WindowObject { public: Shape(SimpleWindow &w, const Position &p, const color c = Red); color GetColor() const; void SetColor(const color c); virtual void Draw(); // virtual function! private: color Color; }; Virtual Functions Can be invoked via either a dereferenced pointer or a reference object Actual function to be invoked is determined from the type of object that is stored at the memory location being accessed Can be invoked via either a dereferenced pointer or a reference object Actual function to be invoked is determined from the type of object that is stored at the memory location being accessed Definition of the derived function overrides the definition of the base class version Can be invoked via either a dereferenced pointer or a reference object Actual function to be invoked is determined from the type of object that is stored at the memory location being accessed Definition of the derived function overrides the definition of the base class version Determination of which virtual function to use cannot always be made at compile time Decision is deferred by the compiler to run time Introduces overhead
  • 16. 16 Pure Virtual Function Has no implementationHas no implementation A pure virtual function is specified in C++ by assigning the function the null address within its class definition Has no implementation A pure virtual function is specified in C++ by assigning the function the null address within its class definition A class with a pure virtual function is an abstract base class Convenient for defining interfaces Base class cannot be directly instantiated A Shape Abstract Base Class class Shape : public WindowObject { public: Shape(SimpleWindow &w, const Position &p, const color &c = Red); color GetColor() const; void SetColor(const color &c); virtual void Draw() = 0; // pure virtual // function! private: color Color; };