Friday, August 24, 2007

Object oriented modelling in C - PART 3 - Inheritance

Inheritance is a mechanism by which new and more specialized classes can be defined in terms of existing classes. When a child class (subclass) inherits from a parent class (superclass), the subclass then includes the definitions of all the attributes and methods that the superclass defines. Usually, the subclass extends the superclass by adding its own attributes and methods. Objects that are instances of the subclass contain all data defined by the subclass and its parent classes, and they are able to perform all operations defined by this subclass and its parents.

This kind of class relationship can be implemented in C by embedding the parent class attribute structure as the first member of the child class structure. This structuring results in such an attribute alignment that a pointer to the Child class can always be safely cast (upcast) on the pointer to the Parent class. In particular, this pointer can always be passed to any C function expecting a pointer to the Parent class. (To be strictly correct in C, you should explicitly upcast this pointer.) This means that all methods of parent classes are automatically available to child classes-in other words, they are inherited.

No comments: