Introduction to ad hoc Polymorphism
This module introduces you to the concept of polymorphism and why it is essential to designing code that requires little modification when functionality is added.
you will learn:
- What polymorphism is and why it's useful
- About the two types of ad hoc polymorphism: conversion and overloading
- How to create special conversion member functions to convert from a user-defined type to built-in type
- How the compiler picks the appropriate version of an overloaded function
In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class.
Furthermore, it is the ability to redefine methods for derived classes. Example: Given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes,
such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language (OOPL).
Polymorphism is supported by C++ both at compile time and at run time. As discussed in earlier modules, compile-time polymorphism is achieved by
overloading functions and operators. Run-time polymorphism is accomplished by using inheritance and virtual functions, and these are the topics of this module.
A virtual function is a member function that is declared within a base class and redefined by a derived class. To create a virtual function, precede the function's
declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited, the derived class redefines the virtual function to fit its
own needs. In essence, virtual functions implement the
one interface, multiple methods philosophy that underlies polymorphism.
The virtual function within the base class defines the form of the interface to that function. Each redefinition of the virtual function by a derived class implements its operation as it relates specifically to the derived class.
That is, the redefinition creates a specific method.
When accessed "normally," virtual functions behave just like any other type of class member function. However, what makes virtual functions important and capable of
supporting run-time polymorphism is how they behave when accessed via a pointer.
A base-class pointer can be used to point to an object of any class derived from that base.
When a base pointer points to a derived object that contains a virtual function, C++ determines which version of that function to call based
upon the type of object pointed to by the pointer. And this determination is made at run time.
Thus, when different objects are pointed to, different versions of the virtual function are executed. The same effect applies to base-class references.