Polymorphism in C++

Instructor's Guide


intro polymorphism idioms patterns events summary, Q/A, literature
Polymorphism essentially characterizes the type of a variable, function or object. Polymorphism may be due to overloading, parametrized types or inheritance. Polymorphism due to inheritance is often considered as the greatest contribution of object-oriented languages. This may be true, but the importance of generic (template) types and overloading should not be overlooked.

Overloading

print


  extern void print(int);
  extern void print(float);
  

Generic class -- templates

list< T >


  template< class T > class list { ... }
  list<int>* alist; 
  

Polymorphism by inheritance

shape


  class shape { ... };
  class circle : public shape { ... } 
  shape* s = new circle;
  

slide: Polymorphic type declarations

In slide 1-polymorphism some examples are given of declarations involving polymorphic types. The function print is separately defined for int and float. Also, a generic list class is defined by means by employing templates. The list may be used for any kind of objects, for example integers. Finally, a shape class is defined from which a circle class is derived. An instance of the circle may be referred to by using a shape pointer, because the type shape encompasses circle objects.

The Standard Template Library (STL)

The Standard Template Library for C++ provides a generic library of data structures to store, access and manipulate data. It is a generic library based on templates. In fact, it uses templates in such an aggressive way that the C++ standardization committee was forced to reconsider its definition of the generic template facility in C++. See  [STL].

Standard Template Library

STL



slide: The Standard Template Library

The Standard Template Library (STL) offers containers, to hold objects, algorithms, that act on containers, and iterators, to traverse containers. Algorithms, which are implemented as objects, may use functions, which are also defined as objects, overloading the application operator() method. In addition, STL offers adaptors, to transform objects, and allocators, for memory management.

STL is supported by C++ compilers that adhere to the C++ standard, including Microsoft Visual C++ and the Cygnus/GNU C++ compilers. A more extensive discussion of STL is beyond the scope of this book, but the reader is advised to consult  [STL], which gives an introduction to STL and its history, as well as a thorough course on programming with STL.