Archive - Originally posted on "The Horse's Mouth" - 2006-07-14 17:15:11 - Graham Ellis
I've been preparing some new C++ notes, in particular showing how you can create an array of objects of different derived types, and then call methods on each object and have the run time environment select which particular piece of code is to be run each time around a loop (experienced OO programmers will recognise this as a description of polymorphism)
So many of the textbooks seem to make what is (I admit) always quite a complex example even more complex ... to the extent that newcomers really can neither understand polymorphism nor how it works in C++; "fools rush in" as they say, and I have tried.
A base class of Shape gives rise to two derived classes - Circle and Square.
An application called Polygon sets up an array of Circles and Squares, and uses a getarea method to find the area of each.
This getarea method is defined as a virtual method in the base class, so that an array of shapes CAN be defined on which two different getarea methods can be run depending on which type of shape is the current one at the time.