What is Templates in C++?
Templates in c++ is defined as a blueprint or formula for creating a
generic class or a function. To simply put, you can create a single
function or single class to work with different data types using
templates.
C++ template is also known as generic functions or classes which is a
very powerful feature in C++. A keyword “template” in c++ is used for
the template’s syntax and angled bracket in a parameter (t), which
defines the data type variable.
C++ Tutorial PDF
How do templates work in C++?
Templates in c++ works in such a way that it gets expanded at
compiler time, just like macros and allows a function or class to work on
different data types without being rewritten.
Types of Templates in C++
There are two types of templates in C++
Function template
Class templates
What is the function template in C++?
Function template in c++ is a single function template that works with
multiple data types simultaneously, but a standard function works only
with one set of data types.
C++ Function Template Syntax
1 template<class type>ret-type func-name(parameter list)
2 {
3 //body of the function
}
4
Here, type is a placeholder name for a data type used by the function. It
is used within the function definition.
The class keyword is used to specify a generic type in a template
declaration.
C++ function template example:
Source Code:
#include<iostream.h>
using namespace std;
template<classX>//can replace 'class" keyword by "typename"
keyword
X func( Xa,Xb)
return a;
int main()
count<<func(15,8),,endl;//func(int,int);
count,,func('p','q'),,endl;//func(char,char);
count<<func(7.5,9.2),,endl;//func(double,double)
return();
}
Output:
15
p
7.5
What is class template in c++?
The class template in c++ is like function templates. They are known as
generic templates. They define a family of classes in C++.
Syntax of Class Template
1 template<class Ttype>
2 class class_name
3 {
4 //class body;
}
5
Here Ttype is a placeholder type name, which will be specified when a
class instantiated.
The Ttype can be used inside the body of the class.
Class template in c++ example:
Source Code:
#include<iostream.h>
using namespace std;
template <class C>
class A{
private;
C,a,b;
public:
A(Cx,Cy){
a=x;
b=y;
void show()
count<<"The Addition of"<<a<<"and"<<b<<"is"<<add()<<endl;
C add(){
C c=a+b;
return c;
};
int main(){
Aaddint(8,6);
Aaddfloat(3.5,2.6);
Aaaddouble(2.156,5.234);
[Link]();
cout<<endl;
[Link]();
count<<endl;
return 0;
Output:
The addition of 8 and 6 is 14
Addition of 3.5 and 2.6 is 6.1
The addition of 2.156 and 5.234 is 7.390
Difference between function
overloading and templates in C++?
Function overloading Function Template
This is used when multiple functions This is used when functions do
do similar operations. identical operations.
Function overloading can take Templates cannot take varying
varying numbers of arguments. numbers of arguments.
Advantages of Using Templates in C+
+
Templates are type-safe.
They are generally considered as an improvement over macros
for these purposes.
Templates avoid some common errors found in code that
makes heavy use of function-like macros.
Both templates and macros are expanded at compile time.
They are a good way of making generalisations for APIs.
Disadvantages of Using Templates in
C++
Many compilers do not support nesting of templates.
When templates are used, all codes exposed.
Some compilers have poor support of templates.
Approx all compilers produce unhelpful, confusing error
messages when errors are detected in the template code.
It can make it challenging to develop the template.
Overloading of C++ template
A template function is called that could be created with an
exact match.
Call an ordinary function that has an exact match.
What is Templates Specialization?
Templates Specialization is defined as a mechanism that allows any
programmer to use types as parameters for a class or a function. A
function/class defined using the template is called a generic
function/class, and the ability to use and create generic
functions/classes is one of the critical features of C++.
//A generic sort function
template<class X>
//code to implement quick sort
//Template specilization:A function
//specialized for char data type
template<>
void sort<char>(char arr[],int size)
//code to impletement counting sort
Function Specialization
We have the add() function, which takes two parameters and returns
the same type of data after adding the two args.
Function specialization example:
Source Code:
1 #include <iostream.h>
using namespace std ;
2
3 //max returns the maximum of the two elements of type T, where T is a
4 //class or data type for which operator> is defined.
5 template <class T>
6 T max(T a, T b)
7 {
return a > b ? a : b ;
8 }
9
10 int main()
11 {
12 cout << "max(80, 95) = " << max(10, 15) << endl ;
cout << "max('a', 'z') = " << max('k', 's') << endl ;
13 cout << "max(11.1, 18.2) = " << max(11.1, 18.2) << endl ;
14
15
cout << "max(\"Ahil\", \"Riya\") = " << max("Ahil", "Riya") << endl ;
16 return 0 ;
17 }
18
19
Output:
max(80, 95) = 95
max(‘a’, ‘z’) = z
max(11.1, 18.2) = 18.2
max(“Ahil”, “Riya”) = Riya
Class Specialization
Class specialization example:
Source Code:
1 #include <iostream>
using namespace std;
2
3 template <class T>
4 class Test
5 {
6 // Data memnbers of test
public:
7 Test()
8 {
9 // Initialization of data members
10 cout << "General template \n";
11 }
// Other methods of Test
12 };
13
14 template <>
15 class Test <int>
{
16 public:
17 Test()
18 {
19 // Initialization of data members
20 cout << "Specialized template \n";
}
21 };
22
23 int main()
24 {
25
26
27
28 Test<int> a;
Test<char> b;
29 Test<float> c;
30 return 0;
31 }
32
33
34
Output:
Specialized template
General template
General template
How does template specialisation work?
When we write any template-based function or class, the compiler
creates a copy of that function/class whenever the compiler sees that
being used for a new data type or a new set of data types(in case of
multiple template arguments).
If a specialised version is present, the compiler first checks with the
specialised version and then the main template. The compiler first
checks with the most specialised version by matching the passed
parameter with the data type(s) specified in a specialised version.
new and delete operators in C++ for dynamic memory
Difficulty Level : Easy
Last Updated : 22 Oct, 2021
Dynamic memory allocation in C/C++ refers to performing memory
allocation manually by programmer. Dynamically allocated memory
is allocated on Heap and non-static and local variables get memory
allocated on Stack (Refer Memory Layout C Programs for details).
What are applications?
One use of dynamically allocated memory is to allocate memory
of variable size which is not possible with compiler allocated
memory except variable length arrays.
The most important use is flexibility provided to programmers.
We are free to allocate and deallocate memory whenever we
need and whenever we don’t need anymore. There are many
cases where this flexibility helps. Examples of such cases
are Linked List, Tree, etc.
How is it different from memory allocated to normal
variables?
For normal variables like “int a”, “char str[10]”, etc, memory is
automatically allocated and deallocated. For dynamically allocated
memory like “int *p = new int[10]”, it is programmers responsibility
to deallocate memory when no longer needed. If programmer
doesn’t deallocate memory, it causes memory leak (memory is not
deallocated until program terminates).
How is memory allocated/deallocated in C++?
C uses malloc() and calloc() function to allocate memory
dynamically at run time and uses free() function to free dynamically
allocated memory. C++ supports these functions and also has two
operators new and delete that perform the task of allocating and
freeing the memory in a better and easier way.
This article is all about new and delete operators.
new operator
The new operator denotes a request for memory allocation on the
Free Store. If sufficient memory is available, new operator initializes
the memory and returns the address of the newly allocated and
initialized memory to the pointer variable.
Syntax to use new operator: To allocate memory of any data
type, the syntax is:
pointer-variable = new data-type;
Here, pointer-variable is the pointer of type data-type. Data-type
could be any built-in data type including array or any user defined
data types including structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
// Combine declaration of pointer
// and their assignment
int *p = new int;
Initialize memory: We can also initialize the memory for built-in
data types using new operator. For custom data types a
constructor is required (with the data-type as input) for initializing
the value. Here’s an example for the initialization of both data
types :
pointer-variable = new data-type(value);
Example:
int *p = new int(25);
float *q = new float(75.25);
// Custom data type
struct cust
{
int p;
cust(int q) : p(q) {}
};
cust* var1 = new cust; // Works fine, doesn't require
constructor
OR
cust* var1 = new cust(); // Works fine, doesn't require
constructor
cust* var = new cust(25) // Notice error if you comment
this line
Allocate block of memory: new operator is also used to
allocate a block(an array) of memory of type data-type.
pointer-variable = new data-type[size];
where size(a variable) specifies the number of elements in an
array.
Example:
int *p = new int[10]
Dynamically allocates memory for 10 integers continuously of
type int and returns pointer to the first element of the sequence,
which is assigned to p(a pointer). p[0] refers to first element, p[1]
refers to second element and so on.
Normal Array Declaration vs Using new
There is a difference between declaring a normal array and
allocating a block of memory using new. The most important
difference is, normal arrays are deallocated by compiler (If array is
local, then deallocated when function returns or completes).
However, dynamically allocated arrays always remain there until
either they are deallocated by programmer or program terminates.
What if enough memory is not available during runtime?
If enough memory is not available in the heap to allocate, the new
request indicates failure by throwing an exception of type
std::bad_alloc, unless “nothrow” is used with the new operator, in
which case it returns a NULL pointer (scroll to section “Exception
handling of new operator” in this article). Therefore, it may be good
idea to check for the pointer variable produced by new before using
it program.
int *p = new(nothrow) int;
if (!p)
{
cout << "Memory allocation failed\n";
}
delete operator
Since it is programmer’s responsibility to deallocate dynamically
allocated memory, programmers are provided delete operator by C+
+ language.
Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;
Here, pointer-variable is the pointer that points to the data object
created by new.
Examples:
delete p;
delete q;
To free the dynamically allocated array pointed by pointer-variable,
use following form of delete:
// Release block of memory
// pointed by pointer-variable
delete[] pointer-variable;
Example:
// It will free the entire array
// pointed by p.
delete[] p;
CPP
// C++ program to illustrate dynamic allocation
// and deallocation of memory using new and delete
#include <iostream>
using namespace std;
int main ()
// Pointer initialization to null
int* p = NULL;
// Request memory for the variable
// using new operator
p = new(nothrow) int;
if (!p)
cout << "allocation of memory failed\n";
else
// Store value at allocated address
*p = 29;
cout << "Value of p: " << *p << endl;
// Request block of memory
// using new operator
float *r = new float(75.25);
cout << "Value of r: " << *r << endl;
// Request block of memory of size n
int n = 5;
int *q = new(nothrow) int[n];
if (!q)
cout << "allocation of memory failed\n";
else
for (int i = 0; i < n; i++)
q[i] = i+1;
cout << "Value store in block of memory: ";
for (int i = 0; i < n; i++)
cout << q[i] << " ";
// freed the allocated memory
delete p;
delete r;
// freed the block of allocated memory
delete[] q;
return 0;
Output:
Value of p: 29
Value of r: 75.25
Value store in block of memory: 1 2 3 4 5
main function and command-line arguments
All C++ programs must have a main function. If you try to compile a C++
program without a main function, the compiler raises an error. (Dynamic-
link libraries and static libraries don't have a main function.)
The main function is where your source code begins execution, but before
a program enters the main function, all static class members without
explicit initializers are set to zero. In Microsoft C++, global static objects
are also initialized before entry to main. Several restrictions apply to
the main function that don't apply to any other C++ functions.
The main function:
Can't be overloaded (see Function overloading).
Can't be declared as inline.
Can't be declared as static.
Can't have its address taken.
Can't be called from your program.
The main function signature
The main function doesn't have a declaration, because it's built into the
language. If it did, the declaration syntax for main would look like this:
C++Copy
int main();
int main(int argc, char *argv[]);
If no return value is specified in main, the compiler supplies a return value
of zero.
Standard command-line arguments
The arguments for main allow convenient command-line parsing of
arguments. The types for argc and argv are defined by the language. The
names argc and argv are traditional, but you can name them whatever you
like.
The argument definitions are as follows:
argc
An integer that contains the count of arguments that follow in argv.
The argc parameter is always greater than or equal to 1.
argv
An array of null-terminated strings representing command-line arguments
entered by the user of the program. By convention, argv[0] is the
command with which the program is invoked. argv[1] is the first
command-line argument. The last argument from the command line
is argv[argc - 1], and argv[argc] is always NULL.
To pass command line arguments, we typically define main() with two
arguments : first argument is the number of command line arguments and
second is list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
argc (ARGument Count) is int and stores number of command-line
arguments passed by the user including the name of the program. So if
we pass a value to a program, value of argc would be 2 (one for argument
and one for program name)
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the
arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1]
will contain pointers to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every
element is command -line arguments.
For better understanding run this code on your linux machine.
// Name of program [Link]
#include <iostream>
using namespace std;
int main(int argc, char** argv)
cout << "You have entered " << argc
<< " arguments:" << "\n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << "\n";
return 0;
Output:
You have entered 4 arguments:
./main
geeks
for
geeks
Properties of Command Line Arguments:
1. They are passed to main() function.
2. They are parameters/arguments supplied to the program when it is
invoked.
3. They are used to control program from outside instead of hard coding
those values inside the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[n] points last
argument.
Note : You pass all the command line arguments separated by a space, but
if argument itself has a space then you can pass such arguments by putting
them inside double quotes “” or single quotes ”.
The two arguments are described below:
#1) Argument Count (ARGC)
This is a non-negative integer argument that holds the number of command line
arguments including the program name. Thus if pass a program name is passed then
argc will have the value of 1.
#2) Argument Vector (ARGV)
Argv is an array of character pointers that contains all the command line arguments
passed to the main function. If ARGC is greater than zero, then Argv[0] will contain the
name of the program. Argv [1] to argv [argc -1] will contain the other command line
arguments.
How To Read/Get Command Line Arguments?
Having seen the parameters that hold count and actual command line arguments, let us
see how we can use command line arguments in a C++ program.
Note that we need to run the program from the command line shell in order to get the
complete functionality of command line arguments.
First, let us see the output of the program where we do not specify any command
line arguments.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
cout << "Number of command line arguments (argc) entered: " << argc<<endl;
for (int i = 0; i < argc; ++i)
cout <<"argv["<<i<<"] : "<<argv[i] << "\n";
return 0;
The above code example shows how we can read and parse the command line
arguments.
First, we print the number of command line arguments which is directly given by the first
parameter to the main function, argc. Then using for loop, we loop through the argument
vector argc which is a character array.
This loop runs from 0 to argc as argc is the total number of command line arguments
that were passed to the program during execution.