Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic classes in templates

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);

like image 970
soxarered Avatar asked Mar 20 '11 14:03

soxarered


People also ask

What are templates in polymorphism?

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.

What are polymorphic classes?

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.

Are C++ templates polymorphic?

Templates are not polymorphic. Templates are bound at compile-time, unlike polymorphic objects which are bound at run-time.

Is template an example of polymorphism?

Both function overloading and templates are examples of polymorphism features of OOP.


1 Answers

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)
like image 101
Mihran Hovsepyan Avatar answered Oct 20 '22 03:10

Mihran Hovsepyan