Designing a base class and subclasses, and their extension, in C++
Archive - Originally posted on "The Horse's Mouth" - 2015-01-01 13:06:11 - Graham Ellis
My first technical post for 2015 - looking back at some of last year's new C++ examples.
Oh - OK - I'm writing this on 1st January and these examples were written and uploaded yesterday, so they're nothing like as old as it sounds.
On Monday and Tuesday, I wrote classes from scratch and looked at basic design - see [here]. I then added dynamic memory management via the new keyword for heap allocation, and using a vector to store references or pointers to my objects - see [here].
Yesterday, I wrote an example in which in had a base class that contained the common specifications and code for a number of similar types of objects, andthen looked at how that can be extended to provide similar types of objects without code duplication. For the whole course, I was very much stressing Test Driven Development and Behaviour Driven Development, and so my very first piece of code - [here] - provides a test and a specification of the API (application programmer interface) to ensure it compiles. It won't load into a complete program yet.
In the second example - [here] - I have implemented the base class (called "shape") and the subclasses ("ball" and "box") together with "cube" which further derives from "shape". You'll notice how hardly any code is repeated from one section to another, as the common code is shared as far up the tree as possible. Colour and density don't change with the change of shape, so they're in the common code, whereas the volume does change for a ball and a box. The volume for a cube is simply the volume for a box, as a cube (by our definition) is simply the special case of a box.
When working out whether incoming data (from a file, for example) relates to boxes, cubes or balls, some logic is required. Naturally, that logic falls within the class code which is looked after by our data type programmer, rather than by our application programmer who just wants to say "here is some data - please work out what object type it is and make the object for me". I have provided a solution to this requirement in the next program - [here] via a static (class) method called "factory"). Nothing special in that name - it's just a convention as raw material is passed in (an incoming string, for example) and manufactured produce (or, rather, and object) is returned.
Further testing was added in the next stage, using the text harness from previous days ([here] for the code [here] for the test harness headers and [here] for the test harness code. And the final example [here] shows operator overloading in C++ ... that may not have been a logical extenion to my demonstration, but it's a subject needed to be covered on our C++ courses and it fitted in here during the presentation.