Polymorphism in C++

Unit 3 Β· Topic 3.2⏱ 12 min readπŸ“Š 2 diagrams❓ 5 MCQs

Introduction

Polymorphism means "many forms". It allows a single interface (function/operator) to behave differently based on the type of data or object it operates on.

Two broad categories: compile-time (static binding) and run-time (dynamic binding via virtual functions).

Classification Diagram

Polymorphism classification tree: compile-time (function/operator overloading) and run-time (virtual functions/overriding)

Fig 3.3 β€” Polymorphism splits into compile-time and run-time techniques.

Definition

Polymorphism: The ability of a function, operator or object to take multiple forms depending on context/type.

Compile-Time Polymorphism

Achieved through function overloading and operator overloading. Resolved by the compiler.

int add(int a, int b) { return a+b; }
double add(double a, double b) { return a+b; }
// compiler picks based on argument types

Run-Time Polymorphism

Achieved through virtual functions and function overriding. Resolved at runtime via vtable.

class Base { public: virtual void show(){ cout<<"Base\n"; } };
class Derived : public Base { public: void show(){ cout<<"Derived\n"; } };
int main(){ Base* p=new Derived(); p->show(); /* Derived */ }

UML View

classDiagram Base <|-- Derived Base : +virtual show() Derived : +show()

Fig 3.4 β€” Derived overrides virtual show() of Base.

Important Questions

Short Questions

  1. Define polymorphism.
  2. Difference between compile-time and run-time polymorphism?
  3. What is function overloading?
  4. What is a virtual function?

Long Questions

  1. Explain run-time polymorphism with a C++ example.
  2. Compare static and dynamic binding.

MCQ Practice

1. Which of these gives run-time polymorphism?

  • Function overloading
  • Virtual functions
  • Operator overloading
  • Templates
Answer: virtual functions.

2. Compile-time polymorphism is also called:

  • Static binding
  • Dynamic binding
  • Late binding
  • Runtime binding
Answer: static binding.

3. Virtual functions are resolved at:

  • Compile time
  • Run time
  • Link time
  • Never
Answer: run time via vtable.

4. Function overloading is based on:

  • Return type only
  • Number/type of parameters
  • Function name
  • Access specifier
Answer: number/type of parameters.

5. Which keyword enables run-time polymorphism?

  • override
  • virtual
  • static
  • inline
Answer: virtual.

Quick Revision

  • Polymorphism = many forms.
  • Compile-time: overloading (static binding).
  • Run-time: virtual functions/overriding (dynamic binding).
  • Virtual uses vtable for dispatch.