Page 1
Wink Notes
B.Tech CSE — 2nd Semester
Object Oriented Programming with C++
— Unit - 5 —
1. The Need for Generics
Throughout the previous units, C++ enforced strict type checking. An `int` is an `int`, a `float` is a `float`. If you write a function to swap two integers, and later need to swap two floats, you must write a completely new, overloaded function.
The logic `t=a; a=b; b=t;` is completely identical across all three functions. Rewriting the exact same logic just to change the data type violates the DRY (Don't Repeat Yourself) principle. It bloats the codebase and makes maintenance a nightmare.
The Solution: Templates
Templates introduce Generic Programming. They allow you to write a function or a class ONCE, using a placeholder for the data type. The compiler automatically generates the correct type-specific code when you actually use it.