OOPortal OOPortal


Inheritance/Polymorphism  «Prev  Next»
Lesson 3 Virtual member functions and pure polymorphism
Objective Virtual member functions and how they are used.

C++ Pure Polymorphism

C++ supports virtual member functions. These are functions declared in the base class and redefined in a derived class. When a virtual member function is redefined, it is overridden as opposed to overloaded. We will look at the difference between overriding and overloading later in this module. For now, just think of the difference as semantic.
  1. Virtual member functions can be overridden, and
  2. nonvirtual member functions can be overloaded.
A class hierarchy that is defined by inheritance creates a related set of user-defined types, all of whose objects may be pointed at by a base class pointer. By accessing the virtual function through this pointer, C++ selects the appropriate function definition at runtime.
This is a form of polymorphism called pure polymorphism.



OOP design methodology

Inheritance should be designed into software to maximize reuse and to allow a natural modeling of the problem domain.
The key elements of the OOP design methodology are as follows:
  1. Decide on an appropriate set of types.
  2. Design in their relatedness, and use inheritance to share code.
  3. Use virtual functions to process related objects polymorphically.

Polymorphism

Polymorphism is the provision of a single interface to entities of different types. A polymorphic type is a type whose operations can also be applied to values of some other type or types. There are several fundamentally different kinds of polymorphism. If a function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad hoc polymorphism. Ad hoc polymorphism is supported in many languages using function overloading.

Polymorphism allows you to take advantage of the commonality between related classes, while still giving each class the flexibility to implement specific behavior. Using polymorphism, it is possible to build very flexible and extensible systems. Polymorphism (literally, having multiple shapes) describes a set of objects of different classes with similar behavior.