Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template class vs Abstract class

Tags:

c++

oop

So I started looking back at some of my OOP courses and I found this question: What is the difference between a template class and an abstract class? When should one be used and not the other?

I know that template classes are instantiated the same way as the functions. A copy is created with the template parameters replaced with actual data types. Abstract classes have pure virtual functions and cannot be instantiated. Derived classes must define the virtual functions.

like image 702
Stefan Avatar asked Sep 04 '15 07:09

Stefan


1 Answers

They're both tools that C++ offers to change the implementation and/or behaviour of a part of your application (i.e. extendibility and reuse).

The main difference is that abstract classes (run-time polymorphism) are a run-time mechanism, while templates are a compile-time mechanism. This means that by using abstract classes you can possibly change the behaviour at run-time (e.g, by loading a configuration file at run-time, or by means of plugins). With templates, instead, you bind your implementation at compile-time (i.e., it's the developer that decides statically once and for all the behaviour).

Being a run-time mechanism, abstract classes bring run-time overhead due to virtual functions. Templates don't suffer this issue.

On the other hand, currently (C++14 standard) you cannot specify an interface for your class templates (i.e., you don't have a spec of the classes you can bind to your template and if you try to instantiate a template class binding the wrong class you get incomprehensible compiler errors). An abstract class instead is actually a "specification" of the concrete classes you can use.

like image 154
Daniele Pallastrelli Avatar answered Oct 22 '22 14:10

Daniele Pallastrelli