8

TEMPLATES: CODE SHARING (GENERICITY)

8.1 INTRODUCTION TO CODE SHARING

There are many programming situations where same set of operations is applied on different data types. For example, the following function exchanges the contents of two variables of type int.

image

Now, consider a situation where we also need to exchange the contents of variable of type: float and char. Accordingly, we will have to define the following two functions:

Function for float type variables:

image

Function for char type variables:

It may be noted that 99% of the code in the ...

Get Object-Oriented Programming with C++ now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.