Professional Documents
Culture Documents
Object Oriented Programming: Name: Muhammad Huzaifa Hassan Khan Class: BCE - 4 Enrollment No: 01-132192-043
Object Oriented Programming: Name: Muhammad Huzaifa Hassan Khan Class: BCE - 4 Enrollment No: 01-132192-043
Object Oriented Programming: Name: Muhammad Huzaifa Hassan Khan Class: BCE - 4 Enrollment No: 01-132192-043
TEMPLATES
A template is a simple and a powerful tool in C++. The idea of using the template is that we pass the
data type as a parameter so that we don’t need to write the same code of different types. In simple
term you can create a single function or a class to work with different data types using templates.
Templates are used in larger codebase for the purpose to rerun the code again and again.
1. Function templates
2. Class templates
Function templates:
A single function template can work with different data types at once but, a single normal function can
only work with one set of data types.
#include <iostream>
// template function
int main()
cout << Large(c1, c2) << " has larger ASCII value.";
return 0;
}
A function template starts with the keyword template followed by template parameter/s inside
< >
#include <iostream>
Using namespacestd;
template<class X,class Y> void fun(X a,Y b)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(15,12.3);
return 0;
}
The idea is that source code contains only function/class, but compiled code may multiple copies of
same function /class.
Class template
Class template like function template are useful in when a class defines something that is independent
of the data type.
Syntax
Template<class type>
Class class_name
Another example
#include<iostream>
Template<class T>
Class M {
Public:
T num1 = 5;
T num1=6;
Void add()
};
int main()
A<int>d;
d.add();
return0;
Example
#include<iostream>
To create a file, use either ofstream or fstream class, and specify the name of the file.
#include<iostream>
Int main()
Ofstream myfile(“filename.txt”);
My file.close();
To read the file we use either ifstream or fstream class and the name of class.