Search code examples
c++templatesinheritancepolymorphism

Why make use inheritance and polymorphism instead of function template instances for calling member functions with the same signature?


I'm trying to learn the core features of object-oriented programming, this can be a weird question but i want to ask:

Why make use inheritance and polymorphism instead of function template instances for calling member functions with the same signature?


Solution

  • Templates are a feature that works at compile-time (statically), where the types of all the objects involved can be worked out by reading the code and seeing what each sort of object is.

    Inheritance and polymorphism, on the other hand, are designed for where we can’t know, at compile time, what the types of the objects would be.

    As an example, consider this code:

    Base* ptr = randomCoinTossIsHeads()? new Derived1() : new Derived2();
    ptr->virtualFunction();
    

    Here, there’s no way to know statically (at compile-time) what type of object ptr is pointing at. It has a 50% chance of being a Derived1, and a 50% chance of being a Derived2. This means that we couldn’t use templates here to determine which function to call. Templates assume we know exactly what type of things we’re dealing with when the code is generated, and that isn’t the case here.

    Hope this helps!