This is the third and last post (see earlier basic encapsulation and polymorphism) about object based firmware programming. This is about single inheritance, another important object oriented principle. This is also pretty much as far as I would go with the HW currently available for our embedded projects, low-end 8-bit microcontrollers. Anything further would require even more use of pointers, including function pointers, and I'm not really that comfortable with their heavy use.
The sample code implements a simple Level object type which has only two members, level and currentState. The first one holds a threshold value, the latter indicates wether the latest sample was below the level (currentState = 0), or equal/above (currentState = 1).
Next we have used Level as a parent for another object type, LevelWithOffset. The new object has the Level type as its first member, named super. This gives us possibility to use pointers to both of the object types in similar way. LevelWithOffset object type has an additional offset member. Value of offset is added to set level. In the example code we have two objects, one simple Level and one LevelWithOffset. Constructor is called for both setting the level to 2. The LevelWithOffset object is then further adjusted by setting the offset also to 2.
The main loop calls the notify method for both objects with values from 0 to 4 and outputs the state of both objects. We can see from the test run that the other object switches the state only after the sample is increased by 2 more steps (effect of additional offset).
You can go a long way with this object stuff in C. If you are interested then check out the papers listes below and start working on your skills and creating your own opinion.
Miro Samek, Portable Inheritance and Polymorphism in C, ESP (pdf)
Ron Kreymborg, Single Inheritance Class in C, Dr. Dobbs Journal
Matthew Curreri, Object-Oriented C: Greating Foundation Classes, ESP (part2)