Lesson 26 +35 XP

Polymorphism & the Categories of Polymorphic Techniques

Polymorphism & the Categories of Polymorphic Techniques

Polymorphism ("many forms") is the ability of one name or one interface to work with values of different types. C++ offers several polymorphic techniques: overloading, coercion, templates and virtual functions. This lesson classifies them, both by when the form is chosen (compile time or run time) and by how (the Cardelli-Wegner categories), and introduces polymorphism by parameter and parametric polymorphism, which the next lessons develop.

1. Two Ways to Classify Polymorphism

By binding time

Compile-time (static) polymorphismRun-time (dynamic) polymorphism
Bindingearly (static) binding: the function is chosen by the compilerlate (dynamic) binding: the function is chosen while the program runs
Techniquesfunction overloading, operator overloading, templatesvirtual functions (overriding) through base pointers or references
Information usedthe types written in the codethe actual type of the object at run time
Speedfaster: no run-time lookupslightly slower: one indirect call through the vtable
Flexibilityless: everything fixed at compile timemore: new derived classes work with old code

Classification of polymorphism in C++Classification of polymorphism in C++

By mechanism (Cardelli and Wegner)

CategoryKindIdeaC++ technique
Ad hoc polymorphismOverloadingone name, separate code for each typefunction and operator overloading
Coerciona value is converted to the type a function expectsimplicit conversions, conversion constructors and operators
Universal polymorphismParametricone piece of code works for any type, given as a parametertemplates
Inclusion (subtype)code written for a base type works for every derived typeinheritance with virtual functions

Ad hoc polymorphism works for a limited, explicitly listed set of types, with different code per type. Universal polymorphism works for an unlimited set of types with the same code.

2. Polymorphism by Parameter (Overloading)

In polymorphism by parameter, the same function name is used with different parameter lists, and the compiler selects the version from the number and types of the arguments. This is ad hoc polymorphism, implemented in C++ by function overloading (Lesson 11), operator overloading (Lessons 19-20) and constructor overloading (Lesson 16).

C++
#include <iostream>
using namespace std;

class Printer {
public:
    void print(int i) {
        cout << "int: " << i << endl;
    }
    void print(double d) {
        cout << "double: " << d << endl;
    }
    void print(const char* s) {
        cout << "string: " << s << endl;
    }
    void print(int i, int j) {
        cout << "pair: (" << i << ", " << j << ")" << endl;
    }
};

int main() {
    Printer p;
    p.print(42); // the parameter types select the version
    p.print(3.75);
    p.print("polymorphism");
    p.print(3, 4);
    return 0;
}

Output:

OUTPUT
int: 42
double: 3.75
string: polymorphism
pair: (3, 4)

3. Coercion

Coercion makes one function usable with several types by converting the argument automatically. A function written for double accepts an int because the compiler converts it; a function written for a class accepts a basic type through a conversion constructor (Lesson 21).

C++
#include <iostream>
using namespace std;

class Meters {
    double value;

public:
    Meters(double v) : value(v) {} // conversion constructor: double -> Meters
    double get() const {
        return value;
    }
};

double half(double x) {
    return x / 2;
}
void showLength(const Meters& m) {
    cout << "length = " << m.get() << " m" << endl;
}

int main() {
    cout << "half(7)   = " << half(7) << endl;   // int coerced to double
    cout << "half('A') = " << half('A') << endl; // char coerced to double (65)
    showLength(12.5);                            // double coerced to Meters
    showLength(3);                               // int -> double -> Meters
    return 0;
}

Output:

OUTPUT
half(7)   = 3.5
half('A') = 32.5
length = 12.5 m
length = 3 m

4. Parametric Polymorphism (Templates)

In parametric polymorphism, a function or class is written once, with the type itself as a parameter. The same code then works for any type that supports the operations it uses.

In C++ this is done with templates, and the result is often called generic programming. The compiler generates a separate version (an instantiation) for each type actually used, so it is still compile-time polymorphism.

C++
#include <iostream>
using namespace std;

template <class T>
T largest(T a, T b) { // one definition for every type
    return (a > b) ? a : b;
}

int main() {
    cout << largest(10, 25) << endl;     // T = int
    cout << largest(3.14, 2.71) << endl; // T = double
    cout << largest('x', 'q') << endl;   // T = char
    return 0;
}

Output:

OUTPUT
25
3.14
x
Overloading (ad hoc)Parametric (templates)
a separate body is written for each typeone body for all types
the types are listed by the programmerworks for any type with the needed operations, including future types
bodies may do different thingsthe same algorithm for every type

Function templates and class templates are covered in Lessons 27 and 31.

5. Inclusion (Subtype) Polymorphism

In inclusion polymorphism, a function that accepts a base-class pointer or reference works with objects of every derived class. With virtual functions, the derived class's own version is called, chosen at run time. This is the polymorphism usually meant by "OOP polymorphism" (Lesson 28).

C++
#include <iostream>
using namespace std;

class Animal {
public:
    virtual void speak() const {
        cout << "..." << endl;
    }
    virtual ~Animal() {}
};
class Dog : public Animal {
public:
    void speak() const {
        cout << "Woof" << endl;
    }
};
class Cat : public Animal {
public:
    void speak() const {
        cout << "Meow" << endl;
    }
};

void makeItSpeak(const Animal& a) { // written once, for the base type
    a.speak();                      // the right version is chosen at run time
}

int main() {
    Dog d;
    Cat c;
    Animal generic;
    makeItSpeak(d);
    makeItSpeak(c);
    makeItSpeak(generic);
    return 0;
}

Output:

OUTPUT
Woof
Meow
...

6. Summary of Polymorphic Techniques in C++

TechniqueCategoryBindingLesson
Function overloadingad hoc (overloading)compile time11
Operator overloadingad hoc (overloading)compile time19, 20
Implicit and user-defined conversionsad hoc (coercion)compile time7, 21
Function and class templatesuniversal (parametric)compile time27, 31
Virtual functionsuniversal (inclusion)run time28, 29
💡 Tip

Key points to remember

  • Compile-time (early binding): overloading and templates. Run-time (late binding): virtual functions.
  • Ad hoc = overloading + coercion (different code or conversions per type). Universal = parametric + inclusion (same code for many types).
  • Polymorphism by parameter: the argument list selects the overloaded function.
  • Parametric polymorphism: templates, where the type is a parameter.
  • Inclusion polymorphism: base pointer/reference + virtual function = derived version at run time.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is polymorphism? Classify the polymorphic techniques available in C++. (10 Marks)
  • Write: the definition, the compile-time vs run-time table, the Cardelli-Wegner table, the diagram, and one example for each technique.
  • Q2. Differentiate between compile-time and run-time polymorphism. (5 Marks)
  • Q3. What is parametric polymorphism? How is it different from overloading? (5 Marks)
  • Write: templates with the largest program, and the comparison table.
  • Q4. Explain polymorphism by parameter with an example. (2.5 Marks)
  • Q5. What is coercion? (2.5 Marks)