0% found this document useful (0 votes)
22 views25 pages

UNIT 03 - Lecture 27 - Templates

The document discusses function and class templates in C++. Templates allow functions and classes to work with different data types. The key points covered include syntax for class and function templates, inheritance of class templates, and an example of a simple calculator program using class templates.

Uploaded by

Jelsteen J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views25 pages

UNIT 03 - Lecture 27 - Templates

The document discusses function and class templates in C++. Templates allow functions and classes to work with different data types. The key points covered include syntax for class and function templates, inheritance of class templates, and an example of a simple calculator program using class templates.

Uploaded by

Jelsteen J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Course: Object Oriented Programming using C++ (22CAU04A)

 Programme (s) : BCA

 Class : I B.C.A ‘A’

 Semester : II

 Unit & Lecture : 3 & 27

 Facilitator : Prof. J. JELSTEEN

SKASC 1
Topic to be Discussed

Function & Class Templates


Templates
• Templates support generic programming, which allows to
develop reusable software components such as function,
class, etc.
• Supporting different data types in a single framework.
• A template in C++ allows the construction of a family of
template functions and classes to perform the same
operation on different data types.
• The templates declared for functions are called function
templates and those declared for classes are called class
templates. It allows a single template to deal with a generic
data type T.
Class Templates
• Class can also be declared to operate on different data
types. Such class are called class templates.

• A class template specifies how individual classes can be


constructed similar to normal class specification.

• These classes model a generic class which support similar


operations for different data types.
Class Templates
Syntax :

template <class T1, class T2, …..> class class_name


{
T1 data1; // data items of template type
void func1 (T1 a, T2 &b); // function of template argument
T func2 (T2 *x, T2 *y);
}
Example : void push(const int
Class charstack &element);
{ char array[25]; int pop(void);
unsigned int top; public: unsigned int getsize
(void) const;
charstack();
};
void push(const char
Class doublestack
&element);
{ double array[25];
char pop(void); unsigned int
unsigned int top;
getsize
public:
(void) const;
doublestack(); void
};
push(const double
Class intstack
&element);
{ int array[25];
double pop(void);
unsigned int top; public:
unsigned int getsize
intstack(); (void) const;
};
• In the previous example, a separate stack class is required for
each and every data types. Templates declaration enables
substitution of code for all the three declarations of stacks with a
single template class as follows :

template<class T> class datastack


{ T array[25];
unsigned int top; public:
doublestack();
void push(const double &element);
double pop(void);
unsigned int getsize (void) const;
};
Inheritance of ClassTemplate
Use of templates with respect to inheritance involves the
followings :
•Derive a class template from a base class, which is a
template class.

•Derive a class template from a base class, which is a


template class, add more template members in the
derived class.
Inheritance of ClassTemplate
Use of templates with respect to inheritance involves the
followings :
•Derive a class from a base class which is not a template,
and template member to that class.
•Derive a class from a base class which is a template
class and restrict the template feature, so that the
derived class and its derivatives do not have the
template feature.
The syntax for declaring derived classes from template-
based base classes is as :

template <class T1, …..> class baseclass


{
// template type data and functions
};
template <class T1, …..>
class derivedclass : public baseclass <T1, ….>
{
// template type data and functions
};
Simple calculator using Class template
#include <iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
Simple calculator using Class template
T add() { return num1 + num2; }

T subtract() { return num1 - num2; }

T multiply() { return num1 * num2; }

T divide() { return num1 / num2; }


};
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
cout << "Int results:" << endl;
intCalc.displayResult();
cout << endl << "Float results:" << endl;
floatCalc.displayResult();
return 0;
}
Simple calculator using Class template
Output

Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2

Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2
In the above program, a class template Calculator is
declared.

• The class contains two private members of type T: num1 &


num2, and a constructor to initalize the members.
• It also contains public member functions to calculate the
addition, subtraction, multiplication and division of the
numbers which return the value of data type defined by
the user. Likewise, a function displayResult() to display the
final output to the screen.
• In the main() function, two different Calculator objects
intCalc and floatCalc are created for data types: int and
float respectively. The values are initialized using the
constructor.
• Notice we use <int> and <float> while creating
the objects. These tell the compiler the data type
used for the class creation.

• This creates a class definition each for int and


float, which are then used accordingly.

• Then, displayResult() of both objects is called


which performs the Calculator operations and
displays the output.
Function Templates
• There are several functions of considerable importance which
have to be used frequently with different data types.
• The limitation of such functions is that they operate only
on a particular data type.
• It can be overcome by defining that function as a function
template or generic function.
• Syntax:
template <class T, …..>
returntype function_name (arguments)
{
…… // body of template function
……
}
Ex : Multipe swap functions Void main()
#include<iostream.h> {
Void swap(char &x, char &y) char ch1, ch2;
{ char t; cout<<“\n Enter values : ”;
t = x; x = y; y = t; cin>>ch1>>ch2;
} swap(ch1,ch2);
Void swap(int &x, int &y) cout<<“\n After swap ch1 =
{ int t; ”<<ch1<<“ ch2 = ”<<ch2;
t = x; x = y; y = t; int a, b;
} cout<<“\n Enter values : ”;
Void swap(float &x, float &y) cin>>a>>b;
{ float t; swap(a,b);
t = x; x = y; y = t; cout<<“\n After swap a =
} ”<<a<<“ b = ”<<b;
float c, d; Output:
cout<<“\n Enter values
: ”; cin>>c>>d; Enter values : R K After swap
swap(c,d); ch1 = K ch2 = R
cout<<“\n After swap c = Enter values : 5 10 After swap
”<<c<<“ d = ”<<d; a = 10 b = 5
} Enter values : 20.5 99.3 After
swap c = 99.3
d = 20.5
Generic fuction for swapping int a, b;
cout<<“\n Enter values :
#include<iostream.h> ”; cin>>a>>b;
Template<class T> swap(a,b);
Void swap(T &x, T &y) cout<<“\n After swap a =
{ T t; ”<<a<<“ b = ”<<b;
t = x; x = y; y = t; float c, d;
} cout<<“\n Enter values :
Void main() ”; cin>>c>>d;
{ swap(c,d);
char ch1, ch2; cout<<“\n After swap c =
cout<<“\n Enter values : ”; ”<<c<<“ d = ”<<d;
}
cin>>ch1>>ch2;
output :
swap(ch1,ch2);
same as previous example
cout<<“\n After swap ch1 =
”<<ch1<<“ ch2 = ”<<ch2;
Function and FunctionTemplate
• Function templates are not suitable for handling all data
types, and hence, it is necessary to override function
templates by using normal functions for specific data types.

Ex: #include<iostream.h> else


#include<string.h> template return b;
<class T> }
T max(T a, T b) void main()
{ if(a>b) return a; {
else char ch,ch1,ch2;
return b; cout<<“\n Enter two
} char value : ”;
char *max(char *a, char *b) cin>>ch1>>ch2;
{ if(strcmp(a,b)>0) ch=max(ch1,ch2);
return a; cout<<“\n max value ”
<<ch;
int a,b,c; Output :
cout<<“\n Enter two int Enter two char value : A
values : ”; Z Max value : Z
cin>>a>>b; c=max(a,b); Enter two int value : 12 20
cout<<“\n max value : ”<<c; Max value : 20
char str1[20],str2[20]; Enter two char value : Tejaswi
cout<<“\n Enter two str Rajkumar Max value : Tejaswi
values : ”;
cin>>str1>>str2; cout<<“\n
max value : ”
<<max(str1,str2);

}
• In the above example if we not use the normal function,
when a statement call such as, max(str1,str2)
• It is executed, but it will not produce the desired result.
The above call compares memory addresses of strings
instead of their contents.
• The logic for comparing strings is different from
comparing integer and floating point data types.
• It requires the normal function having the definition but
not the function template.
• We can use both the normal function and function
template in a same program.
Overloaded Function Templates

• The function template can also be overloaded with


multiple declarations.

• It may be overloaded either by functions of its mane


or by template functions of the same name.

• Similar to overloading of normal functions,


overloaded functions must differ either in terms of
number of parameters or their types.
Ex : #include<iostream.h> Output :
template <class T> 1
void print(T data) 1.5
{ cout<<data<<endl; } 520
template <class T> 520
void print(T data, int OOP is Great OOP is Great
ntimes) OOP is Great
{ for(int i=0;i<ntimes;i++)
cout<<data<<endl;
}
void main()
{ print(1);
print(1.5);
print(520,2);
print(“OOP is Great”,3)
}
Next Session
Exception Handling

Thank You

You might also like