Parametric Polymorphism

Unit 3 · Topic 3.6

Introduction

Parametric polymorphism allows functions/classes to be parameterized by type, implemented in C++ via templates.

Definition

Parametric polymorphism: code written generically, instantiated for specific types at compile time.

Code Example

template <class T>
T maxVal(T a, T b){ return a>b?a:b; }
int main(){ cout<<maxVal(3,7)<<endl; cout<<maxVal(3.5,2.1)<<endl; }

MCQ Practice

1. Parametric polymorphism is implemented via:

  • Templates
  • Virtual functions
  • Inheritance
  • Overloading
Answer: templates.

2. Resolution occurs at:

  • Compile time
  • Run time
  • Link time
  • Never
Answer: compile time.

3. It is also called:

  • Generic programming
  • Dynamic binding
  • Static binding only
  • None
Answer: generic programming.

4. Templates support:

  • Multiple type params
  • Only one type
  • Only int
  • None
Answer: multiple.

5. STL is based on:

  • Templates
  • Inheritance
  • Virtual functions
  • None
Answer: templates.

Quick Revision

  • Parametric polymorphism = templates.
  • Compile-time instantiation.
  • Generic programming.