Friday, January 11, 2008

Design and Implementation Idea of POLYMORPHISM in C [ non - object oriented language] Part II

Design Document -

Here we are required to create a stack which can have element of different types.

Important notes -

In order to apply Objected Oriented Programming concepts to C code, classes are mapped to structs and attributes to struct members and methods to function pointers.
C language has the ability to store pointers for functions as a basic data type, and the ability to call a function from such a function pointer. We can associate with each instance (objects of structures) a table of functions. When a method call on a particular instance is executed, the function table for that instance (actually these tables are shared among the instances of a class), is used to find the proper function to execute.

Define objects

Here I have defined some Structures “general type”, “specific type 1”,” specific type 2”, etc. General type is like the super class from which other specific type classes are formed i.e. like sub classes. Each object has the appropriate data fields. Here is no type field associated with a structure and it is substituted by (at struct offset 0--the first field) with a vtable "pointer to an array of pointers to functions returning int."

There are only two functions associated with each object. Those are get () method and print () method. Get () is used to take input of the data fields of object and print is used for outputting those data fields.


Define vtables - actual polymorphism implementation

1.Virtual tables "general type vtable", "specific type 1 vtable", "specific type 2 vtable" and others are designed. Since there are no defined methods on General type object, that vtable is empty. I have just put a null pointer in the table.

2.The various constructors *_ctor() methods of objects are implemented such that they set the vtable pointer of the appropriate object.

3.#define constants are set up to identify offsets within the vtables. For example, the get() method will always be first in "specific type 1 vtable", "specific type 2 vtable" and others since it is the first (and only) method in those objects.
a.Example : #define METHOD_GET 0

4.The size of a class’s vtable is the maximum number of methods in its interface.



The pattern for invoking a method is:

(*(*object->vtable)[method-index])(object);


xoxo
aL


No comments: