Inheritance is the ability to derive new structures based on existing structures in order to reuse and organize code. You can implement single inheritance in C very simply by literally embedding the base structure as the first member of the derived structure. For example, Figure 1(a) shows the structure ScoreEvt derived from the base structure QEvent by embedding the QEvent instance as the first member of ScoreEvt. To make this idiom better stand out, I always name the base structure member super.
As shown in Figure 1(b), such nesting of structures always aligns the data member super at the beginning of every instance of the derived structure. In particular, this alignment lets you treat a pointer to the derived ScoreEvt structure as a pointer to the QEvent base structure. Consequently, you can always safely pass a pointer to ScoreEvt to any C function that expects a pointer to QEvent. (To be strictly correct in C, you should explicitly cast this pointer. In OOP such casting is called upcasting and is always safe.) Therefore, all functions designed for the QEvent structure are automatically available to the ScoreEvt structure as well as other structures derived from QEvent. Figure 1(c) shows the UML class diagram depicting the inheritance relationship between ScoreEvt and QEvent structures.
QP uses single inheritance quite extensively not just for derivation of events with parameters, but also for derivation of state machines and active objects. Of course, the C++ version of QP uses the native C++ support for class inheritance rather than "derivation of structures".
Copyright © 2002-2011 Quantum Leaps, LLC. All Rights Reserved.