Question:

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
collegedunia
Verified By Collegedunia

The Correct Option is D

Solution and Explanation

Templates are a fundamental feature of C++ that support generic programming.
Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types.
The main purpose of templates is to allow a programmer to write a single function or class that can work with any data type. This avoids code duplication.
For example, instead of writing separate `sort()` functions for an array of integers, an array of floats, and an array of strings, you can write a single `sort()` function template that works for any data type that supports comparison.
Let's analyze the options:
(A) & (B) While templates can sometimes lead to performance improvements due to compile-time optimizations, their primary purpose is not performance itself, but code reusability and type safety.
(C) Function overriding is a concept related to polymorphism and inheritance, not templates.
(D) This option accurately describes the purpose of templates: to create generic functions and classes that can operate on various data types without having to rewrite the code for each type.
Was this answer helpful?
0
0