« Effective web campaign? | Main | undefined reference to typeinfo - C++ error message »

July 14, 2006

Simple polymorphism example - C++

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 decription 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 Cirles 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.

Source Code

Posted by gje at July 14, 2006 05:15 PM

Comments

Post a comment

! Comment registration is required but no TypeKey token has been given in weblog configuration!
Well House Consultants Ltd. Copyright 2008