Let's say we have a class hierarchy where we have a generic Animal
class, which has several classes directly inherit from it (such as Dog
, Cat
, Horse
, etc..).
When using templates on this inheritance hierarchy, is it legal to just use SomeTemplateClass<Animal>
and then shove in Dogs and Cats and Horses into this templated object?
For example, assume we have a templated Stack
class, where we want to host all sorts of animals. Can I simply state Stack<Animal> s; Dog d; s.push(d); Cat c; s.push(c);
Compile-time polymorphism is provided by templates in C++. A template function or class can take any type which conforms to a prototype, usually called a "concept". Unlike base classes and virtual functions, the prototype is implicit: the prototype is defined only by how the type is used by the template function/class.
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks.
Templates are not polymorphic. Templates are bound at compile-time, unlike polymorphic objects which are bound at run-time.
Both function overloading and templates are examples of polymorphism features of OOP.
Answer of your question if No. But you can use SomeTemplateClass<Animal*>
and pass pointers of objects of derived classes to it.
For example, if you have a templated Stack class, where you want to host all sorts of animals. You can simply do following:
Stack<Animal*> s;
Dog d;
s.push(&d);
Cat c;
s.push(&c)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With