Class Templates in C++
Class Templates in C++
A class templates in C++ is a simple and very powerful tool. The easy idea is to pass data type as a parameter so that we do not need to write the same code for different data types.
There are two ways to implement templates
-
- Function Templates
- Class Templates
1. Function Templates
Write the generic function that can be used for various data types.
Examples : sort(), max(), min(), printArray().
Program of a function template
#include <iostream> using namespace std; template <typename T> T myMax(T x, T y) { return (x > y)? x: y; } int main() { cout << myMax<int>(3, 7) << endl; cout << myMax<double>(3.0, 7.0) << endl; cout << myMax<char>('g', 'e') << endl; return 0; }
Output
7 7 g
2. Class Templates
When a class defines something that is independent of the data type then the class templates are used
Class templates is useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
Program of class templates
#include <iostream> using namespace std; template <typename T> class Array { private: T *ptr; int size; public: Array(T arr[], int s); void print(); }; template <typename T> Array<T>::Array(T arr[], int s) { ptr = new T[s]; size = s; for(int i = 0; i < size; i++) ptr[i] = arr[i]; } template <typename T> void Array<T>::print() { for (int i = 0; i < size; i++) cout<<" "<<*(ptr + i); cout<<endl; } int main() { int arr[5] = {1, 2, 3, 4, 5}; Array<int> a(arr, 5); a.print(); return 0; }
Output
1 2 3 4 5
Read more, Virtual function in C++