Question:medium

What is the main purpose of templates in C++?

Show Hint

Think of templates as "blueprints" for functions or classes. You write the blueprint once, and the compiler uses it to generate the specific version of the function or class you need for each data type you use it with.
Updated On: Jul 2, 2026
  • To improve runtime performance
  • To speed up program execution
  • To enable function overriding
  • To define functions and classes that can operate on different data types
Show Solution

The Correct Option is D

Solution and Explanation

Step 1: Think about the problem templates are meant to solve.
Without templates, a programmer who needs a sort function or a max function for integers, floats, and strings would have to write nearly identical code three separate times, once for every data type.
Step 2: See how templates remove that repetition.
A template lets you write the function or class logic exactly once, using a placeholder type parameter, and the compiler generates the type-specific version automatically whenever the template is actually used with a concrete type.
Step 3: Rule out the distractor options.
Templates are fundamentally about writing generic, reusable code rather than about speeding up execution, and overriding is a completely separate concept tied to inheritance and virtual functions, not to templates.
\[ \boxed{\text{To define functions and classes that can operate on different data types}} \]
Was this answer helpful?
0