This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing...

90
This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how to implement and use the simplest kinds of templates: template functions . Template Functions Template Functions Template Functions

Transcript of This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing...

Page 1: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes.

This presentation shows how to implement and use the simplest kinds of templates: template functions.

Template FunctionsTemplate FunctionsTemplate FunctionsTemplate Functions

Template Functions

Page 2: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Template functionsTemplate functions

Sometimes as we are designing or testing Sometimes as we are designing or testing software, we find a need for a single algorithm software, we find a need for a single algorithm that can be applied to objects of different data that can be applied to objects of different data typestypes

We want to be able to describe the algorithm We want to be able to describe the algorithm without having to specify the data types of the without having to specify the data types of the items being manipulated.items being manipulated.

Such an algorithm is referred to as a generic Such an algorithm is referred to as a generic algorithm. algorithm.

C++ supports this using: C++ supports this using: function overloadingfunction overloading and and template functionstemplate functions

Page 3: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function overloading Function overloading continuedcontinued

In previous lectures we introduced In previous lectures we introduced function overloading, i.e. the use of function overloading, i.e. the use of the same name for different the same name for different functions as long as their parameter functions as long as their parameter types are sufficiently different for the types are sufficiently different for the compiler to tell them apart compiler to tell them apart

Lets look at an example to remind Lets look at an example to remind ourselvesourselves

Page 4: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function overloading Function overloading continuedcontinued

To print six data types we could To print six data types we could write:write:

void PrintInt(int n){void PrintInt(int n){

cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;

cout<<“Value is ” << n << endl;cout<<“Value is ” << n << endl;

}}

Page 5: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function overloading Function overloading continuedcontinued

void PrintChar(char n){void PrintChar(char n){

cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;

cout<<“Value is ” << n << endl;cout<<“Value is ” << n << endl;

}}

void PrintFloat(float n){void PrintFloat(float n){

cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;

cout<<“Value is ” << n << endl;cout<<“Value is ” << n << endl;

}}

Page 6: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function overloading Function overloading continuedcontinued

void PrintDouble(double d){void PrintDouble(double d){

cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;

cout<<“Value is ” << d << endl;cout<<“Value is ” << d << endl;

}}

..

..

..

Page 7: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

The solution to previous The solution to previous problemproblem

Instead of having different names for all Instead of having different names for all these similar functions we can use these similar functions we can use function overloading by giving them all the function overloading by giving them all the same name printsame name print

void Print(int n)void Print(int n){{cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;cout<<“Value is ” << n << endl;cout<<“Value is ” << n << endl;}}

Page 8: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

The solution continuedThe solution continued

void Print(char n){void Print(char n){cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;cout<<“Value is ” << n << endl;cout<<“Value is ” << n << endl;}}void Print(float x){void Print(float x){cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;cout<<“Value is ” << x << endl;cout<<“Value is ” << x << endl;}}....

Page 9: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

The solution continuedThe solution continued

The code that calls these functions now The code that calls these functions now looks like thislooks like this

Print(someInt);Print(someInt); Print(someChar);Print(someChar); Print(someFloat);Print(someFloat); We can think of Print as a generic algorithm We can think of Print as a generic algorithm

in the sense that the algorithm itself-that of in the sense that the algorithm itself-that of printing the string “***Debug***” and then printing the string “***Debug***” and then the value of a variable is independent of the the value of a variable is independent of the data type of the variable being printed. data type of the variable being printed.

Page 10: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

How does this workHow does this work

When our program is compiled the When our program is compiled the compiler encounters six different functions compiler encounters six different functions named Print but gives them six different named Print but gives them six different names internally. names internally.

We do not know those names but for the We do not know those names but for the sake of discussion let us assume the sake of discussion let us assume the names are Print_int, Print_char and so on. names are Print_int, Print_char and so on. When the compiler encounters When the compiler encounters Print(someVar)Print(someVar)

Page 11: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

How does this work How does this work continuedcontinued

The compiler must determine which of our The compiler must determine which of our six functions to invoke, to do so the compiler six functions to invoke, to do so the compiler compares the type of the actual argument compares the type of the actual argument with the types of the formal parameters of with the types of the formal parameters of the six functions.the six functions.

Above if someVar is of type int, then the Above if someVar is of type int, then the compiler generates code to call Print_int (i.e. compiler generates code to call Print_int (i.e. the one requiring an integer), if someVar the one requiring an integer), if someVar was of type float then Print_float is invoked was of type float then Print_float is invoked and so on. and so on.

Page 12: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function Overloading Function Overloading continuedcontinued

Despite the benefits of function overloading Despite the benefits of function overloading in our print function example we still had to in our print function example we still had to supply six distinct function definitionssupply six distinct function definitions

This is Okay for functions with few lines of This is Okay for functions with few lines of code, but what it the functions themselves code, but what it the functions themselves were quite complicatedwere quite complicated

Copy and paste does resolve the matter in Copy and paste does resolve the matter in some sense but we will have to look for a some sense but we will have to look for a better approachbetter approach

Page 13: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Here is a small function that you might write to find the maximum of two integers.

int max(int a, int b){ if (a > b) return a; else return b;}

Finding the Maximum of Two Finding the Maximum of Two IntegersIntegers

Finding the Maximum of Two Finding the Maximum of Two IntegersIntegers

Page 14: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Here is a small function that you might write to find the maximum of two doubles.

double max(double a, double b){ if (a > b) return a; else return b;}

Finding the Maximum of Two Finding the Maximum of Two DoublesDoubles

Finding the Maximum of Two Finding the Maximum of Two DoublesDoubles

Page 15: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Here is a small function that you might write to find the maximum of two Knafns.

Knafn max(Knafn a, Knafn b){ if (a > b) return a; else return b;}

Finding the Maximum of Two Finding the Maximum of Two KnafnsKnafns

Finding the Maximum of Two Finding the Maximum of Two KnafnsKnafns

Page 16: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Suppose your program uses 100,000,000 different data types, and you need a maximum function for each...

int maximum(Knafn a, Knafn b){ if (a > b) return a; else return b;}

One Hundred Million Functions...One Hundred Million Functions...One Hundred Million Functions...One Hundred Million Functions...

int maximum(Foo a, Foo b){ if (a > b) return a; else return b;}int maximum(Poo a, Poo b)

{ if (a > b) return a; else return b;}

int maximum(Noo a, Noo b){ if (a > b) return a; else return b;}

int maximum(Moo a, Moo b){ if (a > b) return a; else return b;}

int maximum(Loo a, Loo b){ if (a > b) return a; else return b;}

int maximum(Koo a, Koo b){ if (a > b) return a; else return b;}

int maximum(Joo a, Joo b){ if (a > b) return a; else return b;}

int maximum(Ioo a, Ioo b){ if (a > b) return a; else return b;}

int maximum(Hoo a, Hoo b){ if (a > b) return a; else return b;}

int maximum(Goo a, Goo b){ if (a > b) return a; else return b;}

int maximum(Doo a, Doo b){ if (a > b) return a; else return b;}

int maximum(Coo a, Coo b){ if (a > b) return a; else return b;}

int maximum(Boo a, Boo b){ if (a > b) return a; else return b;}

int maximum(Knafn a, Knafn b){ if (a > b) return a; else return b;}

int maximum(Foo a, Foo b){ if (a > b) return a; else return b;}int maximum(Poo a, Poo b)

{ if (a > b) return a; else return b;}

int maximum(Noo a, Noo b){ if (a > b) return a; else return b;}

int maximum(Moo a, Moo b){ if (a > b) return a; else return b;}

int maximum(Loo a, Loo b){ if (a > b) return a; else return b;}

int maximum(Koo a, Koo b){ if (a > b) return a; else return b;}

int maximum(Joo a, Joo b){ if (a > b) return a; else return b;}

int maximum(Ioo a, Ioo b){ if (a > b) return a; else return b;}

int maximum(Hoo a, Hoo b){ if (a > b) return a; else return b;}

int maximum(Goo a, Goo b){ if (a > b) return a; else return b;}

int maximum(Doo a, Doo b){ if (a > b) return a; else return b;}

int maximum(Coo a, Coo b){ if (a > b) return a; else return b;}

int maximum(Boo a, Boo b){ if (a > b) return a; else return b;}

int maximum(Knafn a, Knafn b){ if (a > b) return a; else return b;}

int maximum(Foo a, Foo b){ if (a > b) return a; else return b;}int maximum(Poo a, Poo b)

{ if (a > b) return a; else return b;}

int maximum(Noo a, Noo b){ if (a > b) return a; else return b;}

int maximum(Moo a, Moo b){ if (a > b) return a; else return b;}

int maximum(Loo a, Loo b){ if (a > b) return a; else return b;}

int maximum(Koo a, Koo b){ if (a > b) return a; else return b;}

int maximum(Joo a, Joo b){ if (a > b) return a; else return b;}

int maximum(Ioo a, Ioo b){ if (a > b) return a; else return b;}

int maximum(Hoo a, Hoo b){ if (a > b) return a; else return b;}

int maximum(Goo a, Goo b){ if (a > b) return a; else return b;}

int maximum(Doo a, Doo b){ if (a > b) return a; else return b;}

int maximum(Coo a, Coo b){ if (a > b) return a; else return b;}

int maximum(Boo a, Boo b){ if (a > b) return a; else return b;}

Page 17: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

This template function can be used with many data types.

template <class Item>Item max(Item a, Item b){ if (a > b) return a; else return b;}

A Template Function for A Template Function for MaximumMaximum

A Template Function for A Template Function for MaximumMaximum

Page 18: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

When you write a template function, you choose a data type for the function to depend upon...

template <class Item>Item max(Item a, Item b){ if (a > b) return a; else return b;}

A Template Function for A Template Function for MaximumMaximum

A Template Function for A Template Function for MaximumMaximum

Page 19: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

A template prefix is also needed immediately before the function’s implementation:

template <class Item>Item max(Item a, Item b){ if (a > b) return a; else return b;}

A Template Function for A Template Function for MaximumMaximum

A Template Function for A Template Function for MaximumMaximum

Page 20: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Once a template function is defined, it may be used with any adequate data type in your program...

template <class Item>Item max(Item a, Item b){ if (a > b) return a; else return b;}

Using a Template FunctionUsing a Template FunctionUsing a Template FunctionUsing a Template Function

cout << max(1,2);

cout << max(1.3, 0.9);

...

Page 21: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Here is another function that can be made more general by changing it to a template function:

int array_max(int data[ ], size_t n){ size_t i; int answer; assert(n > 0); answer = data[0]; for (i = 1; i < n; i++) if (data[i] > answer) answer = data[i]; return answer;

Finding the Maximum Item in an Finding the Maximum Item in an ArrayArray

Finding the Maximum Item in an Finding the Maximum Item in an ArrayArray

Page 22: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Here is the template function:

template <class Item>Item array_max(Item data[ ], size_t n){ size_t i; Item answer; assert(n > 0); answer = data[0]; for (i = 1; i < n; i++) if (data[i] > answer) answer = data[i]; return answer;}

Finding the Maximum Item in an Finding the Maximum Item in an ArrayArray

Finding the Maximum Item in an Finding the Maximum Item in an ArrayArray

Page 23: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Defining a Function Defining a Function Template Template

In C++ a In C++ a function templatefunction template allows allows you to write a function definition with you to write a function definition with “blanks” left in the definition to be “blanks” left in the definition to be filled in by the calling code. filled in by the calling code.

Most often the “blanks” to be filled in Most often the “blanks” to be filled in are the names of the data types. are the names of the data types.

Here is a function template for the Here is a function template for the Print function met earlierPrint function met earlier

Page 24: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function template definitionFunction template definition

template<class someType>template<class someType>

void Print (SomeType val)void Print (SomeType val)

{{

cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;

cout<<“Value is ” << val << endl;cout<<“Value is ” << val << endl;

}}

Page 25: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function templates Function templates continuedcontinued

This function template begins with This function template begins with template<class SomeType>, and template<class SomeType>, and SomeType is known as the template SomeType is known as the template parameter. parameter.

You can use any identifier for the You can use any identifier for the template parameter, we used template parameter, we used SomeType in this example SomeType in this example

Page 26: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function Template SyntaxFunction Template Syntax

Syntax Syntax

template<templateparamList>FunctionDefinition

Page 27: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

continuedcontinued

Where FunctionDefinition is an ordinary Where FunctionDefinition is an ordinary function definition. function definition.

The full syntax description of The full syntax description of TemplateParamList in C++ is quite TemplateParamList in C++ is quite complicated, and we simplify if for out complicated, and we simplify if for out purposespurposes

TemplateParamList is a sequence of one or TemplateParamList is a sequence of one or more parameter declarations separated by more parameter declarations separated by commas, where each is defined as followscommas, where each is defined as follows

Page 28: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Instantiating a Function Instantiating a Function TemplateTemplate

Given that we have written our Print Given that we have written our Print function template, we can make function template, we can make function calls as followsfunction calls as follows

Print <int> (sum);Print <int> (sum);

Print <char> (initial);Print <char> (initial);

Print <float> (angle);Print <float> (angle);

Page 29: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Continued Continued

In this code the data name enclosed in In this code the data name enclosed in angle brackets is called the template angle brackets is called the template argument. argument.

At compile time the compiler generates At compile time the compiler generates (instantiates) three different functions (instantiates) three different functions and gives each its own internal name. and gives each its own internal name.

The three new functions are called The three new functions are called template functions or generated template functions or generated functions functions

Page 30: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

continuedcontinued

The first time the compiler encounters The first time the compiler encounters Print<float> in the calling code, it Print<float> in the calling code, it generates a new function by substituting generates a new function by substituting float for every occurrence of SomeType in float for every occurrence of SomeType in the function Template:the function Template:

void Print(SomeType val)void Print(SomeType val){{cout<<“***Debug***” << endl;cout<<“***Debug***” << endl;cout<<“Value is ” << val << endl;cout<<“Value is ” << val << endl;}}

SomeType

float

Page 31: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Things to noteThings to note

There are two things to note about template There are two things to note about template functions. First the function template uses functions. First the function template uses the reserved word class in its parameter list the reserved word class in its parameter list i.e., template<class SomeType>.i.e., template<class SomeType>.

However the word class in this context is However the word class in this context is simply required syntax and does not mean simply required syntax and does not mean that the callers template argument must be that the callers template argument must be the name of a C++ class. the name of a C++ class.

You can use the reserved word typename You can use the reserved word typename instead of class if you wishinstead of class if you wish

Page 32: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Program templateFn1.cppProgram templateFn1.cpp

See example TemplateFn1.cppSee example TemplateFn1.cpp The line template <class X>void swapargs(X &a, X The line template <class X>void swapargs(X &a, X

&b) tell the compiler two things that a template is &b) tell the compiler two things that a template is being created and that a generic definition is being created and that a generic definition is beginning. beginning.

Here X is a generic type that is used as a place Here X is a generic type that is used as a place holder. holder.

After the template portion the function swapargs() is After the template portion the function swapargs() is declared using X as the data that will be swapped. declared using X as the data that will be swapped.

In main swapargs() is called using three different In main swapargs() is called using three different type of data, ints, floats and chars. Because type of data, ints, floats and chars. Because swapargs() is a generic function the compiler swapargs() is a generic function the compiler automaticaly creates three versions of swapargs(): automaticaly creates three versions of swapargs(): one for ints, floats and chars respectivelyone for ints, floats and chars respectively

Page 33: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Important termsImportant terms

Generic function-as function Generic function-as function definition preceded by a template definition preceded by a template statement are also called a template statement are also called a template functionfunction

When the compiler creates a specific When the compiler creates a specific version of this function it is said to version of this function it is said to have created a specialization, this is have created a specialization, this is also called a generated functionalso called a generated function

Page 34: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Important pointsImportant points

Since C++ doe not recognize end-of-Since C++ doe not recognize end-of-line as a statement terminator, the line as a statement terminator, the template portion of a template template portion of a template function definition does not have to function definition does not have to be on the same line as the function’s be on the same line as the function’s name. name.

So we could have writtenSo we could have written

Page 35: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Important Important

template <class X> template <class X>

void swapargs(X &a, X &b)void swapargs(X &a, X &b)

{{

X temp;X temp;

temp = a;temp = a;

a=b;a=b;

b=temp;b=temp;

}}

Page 36: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

continuedcontinued

If you use this form it is important to If you use this form it is important to understand that no other statements understand that no other statements can occur between the template can occur between the template statement and the start of the statement and the start of the generic function (template fn). generic function (template fn).

The following program will not The following program will not compilecompile

See TemplateFn2.cppSee TemplateFn2.cpp

Page 37: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

A function with two Generic A function with two Generic typestypes

See example TemplateFn3.cppSee example TemplateFn3.cpp

In this example, the place holder In this example, the place holder types type1 and type2 are replaced types type1 and type2 are replaced by the compiler with the data types by the compiler with the data types int and char*, and double and long int and char*, and double and long respectively when the compiler respectively when the compiler generates specific instances of generates specific instances of myfunc() within mainmyfunc() within main

Page 38: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Point to notePoint to note

REMEMBERREMEMBER: When you create a : When you create a template function you are in essence template function you are in essence allowing the compiler to generate as allowing the compiler to generate as many different versions of that many different versions of that function as are necessary for function as are necessary for handling the various ways that your handling the various ways that your program calls the functionprogram calls the function

Page 39: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Explicitly Overloading a Explicitly Overloading a Generic FunctionGeneric Function

See TemplateFn4.cppSee TemplateFn4.cpp

Even though a generic function overloads itself Even though a generic function overloads itself as needed you can explicitly overload one too. as needed you can explicitly overload one too.

This is called This is called explicit specializationexplicit specialization. If you . If you overload a generic function, then that overload a generic function, then that overloaded function overrides (or “hides) ”the overloaded function overrides (or “hides) ”the generic function relative to that specific generic function relative to that specific version. version.

Page 40: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

ExplanationExplanation

As the comments inside the program As the comments inside the program indicate when swappargs(i,j) is called, it indicate when swappargs(i,j) is called, it invokes the explicitly overloaded version invokes the explicitly overloaded version of swapargs() defined in the program. of swapargs() defined in the program.

Thus the compiler does not generate this Thus the compiler does not generate this version of the generic swapargs() version of the generic swapargs() function because the generic function is function because the generic function is overridden by the explicit overloadingoverridden by the explicit overloading

Page 41: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

New syntax for New syntax for specializatonspecializaton

C++ has introduced syntax that allows C++ has introduced syntax that allows explicit specialization of a function. This is explicit specialization of a function. This is shown below for swapargs()shown below for swapargs()

template <> void swapargs(int &a, int &b){template <> void swapargs(int &a, int &b){int temp;temp=a;int temp;temp=a;a=b;a=b;b=temp;b=temp;cout<< “Inside swapargs int specialization” << cout<< “Inside swapargs int specialization” <<

endl;endl;}}

Page 42: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Explanation Explanation

As you can see the new-style syntax As you can see the new-style syntax uses the template<> construct to uses the template<> construct to indicate specialization. indicate specialization.

The type of data for which The type of data for which specialization is being created is specialization is being created is placed inside the angle brackets placed inside the angle brackets following the function namefollowing the function name

Page 43: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Overloading a Function Overloading a Function TemplateTemplate

In addition to creating explicit overloaded In addition to creating explicit overloaded versions of a generic function, you can versions of a generic function, you can overload the template specification, itself. overload the template specification, itself.

To do so simply create another version of To do so simply create another version of the template that differs from any others the template that differs from any others in its parameter list.in its parameter list.

See TemplateFn5.cppSee TemplateFn5.cpp Here the template for f() is overloaded to Here the template for f() is overloaded to

accept either one or two parametersaccept either one or two parameters

Page 44: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Using standard parameters Using standard parameters with template functionswith template functions

You can mix standard parameters You can mix standard parameters with generic type parameters in a with generic type parameters in a template function. template function.

These non-generic parameters work These non-generic parameters work just like they do with any other just like they do with any other functionfunction

See TemplateFn6.cppSee TemplateFn6.cpp

Page 45: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Explanation Explanation

In the program the function repeat() In the program the function repeat() displays the first argument the displays the first argument the number of times requested by the number of times requested by the second argument. second argument.

Since the first argument is a generic Since the first argument is a generic type, repeat can be used to display type, repeat can be used to display any type of data. any type of data.

The times parameter is a standard The times parameter is a standard call-by-reference parameter. call-by-reference parameter.

Page 46: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Creating a generic abs() Creating a generic abs() FunctionFunction

Lets look again at a function Lets look again at a function computing the absolute value of its computing the absolute value of its argumentargument

See example abs1.cppSee example abs1.cpp Explanation to followExplanation to follow

Page 47: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Generic classesGeneric classes

In addition to generic functions you can also In addition to generic functions you can also define a generic class. define a generic class.

When you do this you create a class that When you do this you create a class that defines all the algorithms used by that class; defines all the algorithms used by that class; however the actual type of the data being however the actual type of the data being manipulated will be specified as a parameter manipulated will be specified as a parameter when objects of that class are created. when objects of that class are created.

Useful when a class uses logic that can Useful when a class uses logic that can generalised, e.g. the same algorithm that generalised, e.g. the same algorithm that maintains a queue of integers will also work maintains a queue of integers will also work for a queue of characters. for a queue of characters.

Page 48: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Syntax Syntax

template <class Ttype> class template <class Ttype> class class_name{class_name{

..

..}}Here Ttype is the placeholder type name, Here Ttype is the placeholder type name,

which will be specified when a class is which will be specified when a class is instantiated.instantiated.

See example queue1.cpp (and explain)See example queue1.cpp (and explain)

Page 49: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Member functionsMember functions

Member functions of a generic class Member functions of a generic class are themselves automatically are themselves automatically generic, you don’t need to use a generic, you don’t need to use a template to explicitly specify them as template to explicitly specify them as such. such.

A character queue and a floating A character queue and a floating point queue are created but any data point queue are created but any data can be used.can be used.

Page 50: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

A template function depends on an underlying data type.

SummarySummarySummarySummary

Page 51: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Polymorphism and Polymorphism and Overloading in C++Overloading in C++

Lecture 8bLecture 8b

Polymorphism and Polymorphism and OverloadingOverloading

Page 52: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

OverviewOverview

OverloadingOverloading Ambiguous function callsAmbiguous function calls Unambiguous function callsUnambiguous function calls PolymorphismPolymorphism

Virtual functionsVirtual functions

Page 53: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Keywords for TodayKeywords for Today

Polymorphism Polymorphism Overloading Overloading Ambiguous Ambiguous Unambiguous Unambiguous Virtual functionsVirtual functions

Page 54: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function overloadingFunction overloading

In C++ two or more functions can share In C++ two or more functions can share the same name as long as their signatures the same name as long as their signatures (i.e. parameter declaration are different). (i.e. parameter declaration are different).

In this set the functions are said to be In this set the functions are said to be overloadedoverloaded, and the process is referred to , and the process is referred to as function overloadingas function overloading

Lets consider an exampleLets consider an example See example Overloading1.cppSee example Overloading1.cpp

Page 55: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Overloading1.cpp exampleOverloading1.cpp example

The program produces the following The program produces the following output:output:

In f(int), i is 10In f(int), i is 10

In f(int,int), i is 10, j is 20In f(int,int), i is 10, j is 20

In f(double), k is 12.23In f(double), k is 12.23

Page 56: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Example continuedExample continued

As one can see f() is overloaded three As one can see f() is overloaded three times i.e. there are three different times i.e. there are three different versions of it, each version requiring versions of it, each version requiring different parameters in the function call.different parameters in the function call.

Because the parameter list is different Because the parameter list is different for each function call the compiler is for each function call the compiler is able to call the correct version of the able to call the correct version of the function. function.

Page 57: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Example continuedExample continued

The compiler uses the type and/or number of The compiler uses the type and/or number of arguments as its guide to determining which arguments as its guide to determining which version of an overloaded function to call. version of an overloaded function to call.

Thus overloaded functions must differ in the Thus overloaded functions must differ in the type and/or number of their parameters.type and/or number of their parameters.

While overloaded functions may have different While overloaded functions may have different return types, the return type alone is not return types, the return type alone is not sufficient to distinguish two versions of a sufficient to distinguish two versions of a function. function.

To better understand this lets look at another To better understand this lets look at another example. example.

Page 58: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Example Overloading2.cppExample Overloading2.cpp

This program creates three similar but This program creates three similar but different functions called abs, each of which different functions called abs, each of which returns the absolute value of its argument. returns the absolute value of its argument.

The compiler knows which function to use in The compiler knows which function to use in each given situation because of the type of each given situation because of the type of the argument. the argument.

Thus the name abs represents the general Thus the name abs represents the general action that is being performed . action that is being performed .

It is left to compiler to choose the correct It is left to compiler to choose the correct specific version for a particular circumstance. specific version for a particular circumstance.

Page 59: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

When do we overload?When do we overload?

When we overload a function, each version of that When we overload a function, each version of that function can perform and activity one desires. That is function can perform and activity one desires. That is there is no rule that states that overloaded functions there is no rule that states that overloaded functions must relate to one another.must relate to one another.

From a stylistic point of view function overloading From a stylistic point of view function overloading implies a relationship. Thus while you could use the implies a relationship. Thus while you could use the same name to overload unrelated functions you should same name to overload unrelated functions you should not. not.

E.g. you could use the name sqr() to create functions E.g. you could use the name sqr() to create functions that return the square of an int and the square root of a that return the square of an int and the square root of a double. But these two operations are different and double. But these two operations are different and applying function overloading in this manner defeats the applying function overloading in this manner defeats the original purpose, this would be considered bad practice. original purpose, this would be considered bad practice.

Page 60: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

A C++ reminderA C++ reminder When C++ was created, overloaded functions When C++ was created, overloaded functions

had to be explicitly declared as such using the had to be explicitly declared as such using the overloadoverload keyword. keyword.

The overload keyword is no longer required or The overload keyword is no longer required or supported by C++. supported by C++.

In fact it is not even defined as a keyword by In fact it is not even defined as a keyword by standard C++. But in older books you may standard C++. But in older books you may encounter it. The general form wasencounter it. The general form was

overload func_name;overload func_name; E.g. you would write overload abs();E.g. you would write overload abs(); Most compilers would not accept this now. Most compilers would not accept this now.

Page 61: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Default Function ArgumentsDefault Function Arguments

In C++ you can give a parameter a In C++ you can give a parameter a default value that is automatically default value that is automatically used when no arguments used when no arguments corresponding to that parameter is corresponding to that parameter is specified in a function call. specified in a function call.

The syntax is similar to variable The syntax is similar to variable initializationinitialization

Page 62: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Example Example

defaultfunction1.cppdefaultfunction1.cpp myfunc() can be called by one of the myfunc() can be called by one of the

three ways shown here:three ways shown here: Myfunc(198.234, ‘A’);Myfunc(198.234, ‘A’); Myfunc(10.1);Myfunc(10.1); Myfunc();Myfunc();

Page 63: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Explaining exampleExplaining example

The first call passes the value The first call passes the value 198.234 to num and ‘A’ to ch198.234 to num and ‘A’ to ch

The second call automatically The second call automatically gives num the value 10.1 and gives num the value 10.1 and allows ch to default to ‘X’allows ch to default to ‘X’

Finally the third call cause both Finally the third call cause both num and ch to default. num and ch to default.

Page 64: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Why use default argument?Why use default argument?

One reason is that default arguments One reason is that default arguments are included in C++ is to enable the are included in C++ is to enable the programmer to manage greater programmer to manage greater complexity. complexity.

To illustrate this lets look at the To illustrate this lets look at the clrscr() example (i.e clrscr() example (i.e defaultfunction2.cpp in the folder)defaultfunction2.cpp in the folder)

Page 65: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

clrscr() example explainedclrscr() example explained

The clrscr() function clears the screen by The clrscr() function clears the screen by outputting a series of line feeds (not the most outputting a series of line feeds (not the most efficient way to do it). efficient way to do it).

Since a very common video mode displays 25 Since a very common video mode displays 25 lines of text the default argument of 25 is lines of text the default argument of 25 is provided.provided.

However since some terminals can display However since some terminals can display more or less than 25 lines you can override more or less than 25 lines you can override the default argument by specifying another the default argument by specifying another explicitlyexplicitly

Page 66: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Things to noteThings to note

The default values must be specified only The default values must be specified only once, and this specification MUST happen the once, and this specification MUST happen the first time the function is declared within the first time the function is declared within the file. file.

In the previous example the default argument In the previous example the default argument was specified in clrscr()’s prototype. was specified in clrscr()’s prototype.

If you try to specify new (or even the same) If you try to specify new (or even the same) default values in clrscr()’s definition the default values in clrscr()’s definition the compiler will give an error messagecompiler will give an error message

Page 67: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Another point to noteAnother point to note

It is important to note that all It is important to note that all parameters that take default parameters that take default values must appear to the right values must appear to the right of those that do not. E.g the of those that do not. E.g the following prototype is invalidfollowing prototype is invalid

void f(int a=1, int b); //wrongvoid f(int a=1, int b); //wrong

Page 68: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Another point to noteAnother point to note

Once you have begun defining Once you have begun defining parameters that take default values, parameters that take default values, you cannot specify a non-defaulting you cannot specify a non-defaulting parameter. That is a declaration like parameter. That is a declaration like the following:the following:

int myfun(float f, char str, int i=10, int int myfun(float f, char str, int i=10, int j)j)

Since i has been given a default value Since i has been given a default value j, must also be given one too.j, must also be given one too.

Page 69: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Default arguments vs Default arguments vs OverloadingOverloading

Suppose we want to create two Suppose we want to create two versions of the standard strcat versions of the standard strcat function. function.

One version will operate like strcat() One version will operate like strcat() and concatenate the entire contents and concatenate the entire contents of one string onto another. of one string onto another.

The other version will take a third The other version will take a third argument that specifies the number argument that specifies the number of characters to concatenate.of characters to concatenate.

Page 70: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

The definition of mystrcat()The definition of mystrcat()

void mystrcat(char *s1, char *s2, int len);void mystrcat(char *s1, char *s2, int len); void mystrcat(char *s1, char *s2);void mystrcat(char *s1, char *s2);

The first version will copy len characters The first version will copy len characters from s2 to the end of s1. The second from s2 to the end of s1. The second version will copy the entire string pointed version will copy the entire string pointed to by s2 onto the end of the string pointed to by s2 onto the end of the string pointed to by s1 and will thus operate like strcat()to by s1 and will thus operate like strcat()

See example See example DefaultArguementsVsOverloading1.cppDefaultArguementsVsOverloading1.cpp

Page 71: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

DefaultArguements Vs DefaultArguements Vs Overloading1.cpp continuedOverloading1.cpp continued

Here mystrcat() concatenates up to len Here mystrcat() concatenates up to len characters from the string pointed to by s2 characters from the string pointed to by s2 onto the end of the string pointed to by s1, onto the end of the string pointed to by s1, if len is zero as it will be when it is allowed if len is zero as it will be when it is allowed to default, mystrcat() concatenates the to default, mystrcat() concatenates the entire string pointed to by s2 onto s1. entire string pointed to by s2 onto s1.

So when len=0 the function behaves like So when len=0 the function behaves like strcat(), so default constructors are short-strcat(), so default constructors are short-cut ways of function overloading. cut ways of function overloading.

Page 72: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Function overloading and Function overloading and ambiguityambiguity

Common type of C++ error related Common type of C++ error related to function overloading is ambiguity. to function overloading is ambiguity.

It is possible to create a situation It is possible to create a situation when a compiler is unable to when a compiler is unable to determine which correctly defined determine which correctly defined overloaded function to choose. overloaded function to choose.

Ambiguous statements are errors Ambiguous statements are errors and thus the program will not and thus the program will not compile. compile.

Page 73: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Ambiguity continuedAmbiguity continued

The most common type of mistake is The most common type of mistake is that of automatic type conversions. that of automatic type conversions.

C++ will automatically attempt to C++ will automatically attempt to convert the type of the arguments convert the type of the arguments used to call a function into the type used to call a function into the type of the parameters defined by the of the parameters defined by the function.function.

Page 74: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Example Example

int myfunc(double d);int myfunc(double d);

..

..

cout << myfunc(‘c’); // no error,cout << myfunc(‘c’); // no error,

//conversion applied//conversion applied

The character c will be converted into its The character c will be converted into its double equivalent. double equivalent.

Page 75: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

DemonstrationDemonstration

See example FnAmbiguityandOver1.cppSee example FnAmbiguityandOver1.cpp

This program does not compile, there is an This program does not compile, there is an ambiguity when we write ambiguity when we write myfunc(10);myfunc(10);The compiler has no way of knowing whether to The compiler has no way of knowing whether to

convert to float or doubleconvert to float or doubleThe ambiguity is not caused by the overloading The ambiguity is not caused by the overloading

of myfunc but by the specific call to myfunc()of myfunc but by the specific call to myfunc()

Page 76: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Demonstration Demonstration

See example See example

FnAmbiguityandOver2.cppFnAmbiguityandOver2.cpp

Compiler does not know whether to Compiler does not know whether to convert to char or to unsigned charconvert to char or to unsigned char

Page 77: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Pointers to derived classesPointers to derived classes

In C++ a base class pointer may also In C++ a base class pointer may also be used to point to an object of any be used to point to an object of any class derived from that baseclass derived from that base

Suppose we have base class B_class Suppose we have base class B_class and a class called D_class which is and a class called D_class which is derived from B_class. derived from B_class.

In C++ any pointer declared as a In C++ any pointer declared as a pointer to B_class can also be a pointer to B_class can also be a pointer to D_classpointer to D_class

Page 78: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Pointers to derived classesPointers to derived classes

B_class *p;B_class *p; B_class B_obj;B_class B_obj; D_class D_obj;D_class D_obj;

The following are now validThe following are now valid

p=&B_obj;p=&B_obj;

p=&D_obj;p=&D_obj;

Page 79: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Example continuedExample continued

In this example p can be used to to In this example p can be used to to access all elements of D_ob inherited access all elements of D_ob inherited from B_ob. However elements from B_ob. However elements specific to D_ob can not be specific to D_ob can not be references with p references with p

See example PointerInheritance.cppSee example PointerInheritance.cpp

Page 80: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Explanation Explanation

In PointerInheritance1.cpp, the pointer p In PointerInheritance1.cpp, the pointer p is defined as a pointer to B_class. is defined as a pointer to B_class.

However it can point to an object of the However it can point to an object of the derived class D_class and can be used to derived class D_class and can be used to access those elements of the derived access those elements of the derived class that are inherited from the base class that are inherited from the base classclass

Recall that the inheritance in done Recall that the inheritance in done publicly publicly

Page 81: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

continuedcontinued

But remember a base class pointer But remember a base class pointer cannot access those elements cannot access those elements specific to the derived class (without specific to the derived class (without type casting) that is why show_title() type casting) that is why show_title() is accessed with the dp pointer which is accessed with the dp pointer which is a pointer to the derived classis a pointer to the derived class

Page 82: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

continuedcontinued

If you want to access elements defined by If you want to access elements defined by the derived class by using a base class the derived class by using a base class pointer you must cast it into a pointer of the pointer you must cast it into a pointer of the derived type. The following line of code will derived type. The following line of code will properly call the show_title() function of properly call the show_title() function of D_objD_obj

((D_class *)p)->show_title();((D_class *)p)->show_title(); The outer set of parentheses is necessary for The outer set of parentheses is necessary for

associating the cast with p and not with the associating the cast with p and not with the return type of show_title(). This code would return type of show_title(). This code would be considered bad code.be considered bad code.

Page 83: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Virtual functionsVirtual functions

Run-time polymorphism is achieved Run-time polymorphism is achieved through a combination of two features:through a combination of two features: Inheritance Inheritance Virtual functionsVirtual functions

A virtual function is declared virtual in a base A virtual function is declared virtual in a base class and redefined in one or more of the class and redefined in one or more of the derived classesderived classes

So each derived class can have its own version So each derived class can have its own version of a virtual functionof a virtual function

Page 84: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Virtual functionsVirtual functions

When a virtual function is called When a virtual function is called through a base class pointer C++ through a base class pointer C++ determines which version of that determines which version of that function to call based upon the type function to call based upon the type of the object pointed to by the of the object pointed to by the pointer.pointer.

This determination is made at run-This determination is made at run-timetime

Page 85: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Declaring virtual functionsDeclaring virtual functions

One declares a virtual function as One declares a virtual function as virtual inside the base class by virtual inside the base class by preceding it declaration with the preceding it declaration with the keyword virtual.keyword virtual.

When a virtual function is redefined When a virtual function is redefined in the derived class the keyword in the derived class the keyword virtual need not be included but it is virtual need not be included but it is not an error to do so.not an error to do so.

Page 86: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Virtual functionsVirtual functions

A class that includes a virtual A class that includes a virtual function is called a polymorphic function is called a polymorphic class. class.

See example virtual1.cppSee example virtual1.cpp

Page 87: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Output of virtual1.cppOutput of virtual1.cpp

The output as we have seen is:The output as we have seen is: BaseBase First derivationFirst derivation Second derivationSecond derivation

Page 88: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Examining the programExamining the program As you can see in base the fn who() is declared As you can see in base the fn who() is declared

virtual. This means that the function can be virtual. This means that the function can be redefined in derived classes, which has been redefined in derived classes, which has been done in the derived classesdone in the derived classes

In main four variables are declared. Since who() is In main four variables are declared. Since who() is declared virtual, C++ determines at run-time declared virtual, C++ determines at run-time which version of who() is referred to by the type which version of who() is referred to by the type of object pointed to by p. of object pointed to by p.

In this case p points to an object type base, so In this case p points to an object type base, so the version of who() in base is executed. the version of who() in base is executed.

When p is assigned the address of first_obj, who() When p is assigned the address of first_obj, who() of this class is now executed. of this class is now executed.

Page 89: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Calling virtual functionsCalling virtual functions

The following is also permittedThe following is also permitted First_obj.who();First_obj.who(); But this ignores polymorphic attributes. But this ignores polymorphic attributes.

Note redefinition of virtual functions requires Note redefinition of virtual functions requires identical definitions as opposed to identical definitions as opposed to overloading where we must alter the overloading where we must alter the signature. signature.

A virtual function must be a member of a A virtual function must be a member of a class and not a friend. class and not a friend.

Page 90: This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.

Virtual function are Virtual function are inheritedinherited

Suppose second_d is derived from Suppose second_d is derived from first_d instead of basefirst_d instead of base

See virtual2.cppSee virtual2.cpp