Unit-4 oop
Unit-4 oop
iMSCIT
Sem-III
221601301
Object Oriented Programming
●
Class Template:
We can define a template for a class. For example, a class
template can be created for the array class that can accept the
array of various types such as int array, float array or double
array.
Function Template
●
Generic functions use the concept of a function template. Generic
functions define a set of operations that can be applied to the various
types of data.
●
The type of the data that the function will operate on depends on the
type of the data passed as a parameter.
●
For example, Quick sorting algorithm is implemented using a generic
function, it can be implemented to an array of integers or array of
floats.
●
A Generic function is created by using the keyword template. The
template defines what function will do.
●
The typename and class are keywords used in templates in C++.
There is no difference between the typename and class keywords.
Syntax of Function Template
●
We can use more than one generic type in the template function by using
the comma to separate the list.
●
Syntax
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
In the above syntax, we have seen that the template function can accept any
number of arguments of a different type.
CLASS TEMPLATE
●
Class Template can also be defined similarly to the Function Template. When a
class uses the concept of Template, then the class is known as generic class.
●
class templates are useful when a class defines something that is independent
of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack,
Queue, Array, etc.
●
Syntax
template<class Ttype>
class class_name
{
}
●
Ttype is a placeholder name which will be determined when the class is
instantiated. We can define more than one generic data type using a comma-
separated list. The Ttype can be used inside the class body.
●
Now, we create an instance of a class
●
class_name<type> ob;
●
where class_name: It is the name of the class.
●
type: It is the type of the data that the class is operating on.
●
ob: It is the name of the object.
CLASS TEMPLATE WITH MULTIPLE
PARAMETERS
●
We can use more than one generic data type in a class template,
and each generic data type is separated by the comma.
●
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
Member Function Templates
●
Member function templates are function templates that are
members of a class or class template. Member functions
can be function templates in several contexts.
●
You can define member function templates in the class or
outside the class.
Overloading Template Functions
●
The function template has the same syntax as a regular function, but it starts
with a keyword template followed by template parameters enclosed inside
angular brackets <>.