Derived classes and vtables: example of creation

Task

We have a parent "class" with virtual functions KNameList and need to create a child class (KNodeNameList).

Parent class

KNameList has the following virtual functions declared in itf/kcont/namelist.h (parent class public interface):

The file itf/kcont/impl.h contains "class protected" part to be used by derived classes.
It has:

Child class: factory method declaration (.h file)

To create child objects we declare a factory method:

It is a function of KXMLNode "class" that creates KNameList objects of our derived KNodeNameList type.

Child class implementation

Child class .c file contains:

All of these objects and functions are static within the file.

  1. Child class structure
  2. struct KNodeNameList {
        KNameList dad;
        struct _xmlAttr* properties;
        struct _xmlNode* children;
    };

  3. Child class virtual functions
  4. static int s_KNodeNameListRelease ( KNodeNameList *self )
    { return kxmlNoErr; }
    
    static int s_KNodeNameListCount ( const KNodeNameList *self, uint32_t *count )
    { return kxmlNoErr; }
    
    static int s_KNodeNameListGet
        ( const KNodeNameList *self, uint32_t idx, const char **name )
    { return kxmlNoErr; }

  5. Virtual table "object"
  6. static KNameList_vt_v1 s_vtKNodeNameList = {
        /* version 1.0 */
        1, 0,
    
        /* start minor version 0 methods */
        ( int ( * ) ( KNameList* ) ) s_KNodeNameListRelease,
        ( int ( * ) ( const KNameList*, uint32_t* ) ) s_KNodeNameListCount,
        ( int ( * ) ( const KNameList*, uint32_t, const char** ) ) s_KNodeNameListGet
        /* end minor version 0 methods */
    };

  7. Factory method definition
  8. int KXMLNodeListAttr ( const KXMLNode *self, struct KNameList const **result ) {
        KNodeNameList* obj = (KNodeNameList*) malloc(sizeof(KNodeNameList));
        int status
    	= KNameListInit(&obj->dad, (const KNameList_vt*) &s_vtKNodeNameList);
        *result = obj;
        return kxmlNoErr;
     }