Thursday 3 December 2020

OOP - Recovering lost class types

 Normally casting is used to convert classes to other classes, however this operation can break the type system.

For example, a "List" may use the class "ListItem". And the "ListItem" is then inherited by the "Item" class. So we may store "Item" classes in the "List" class.

Using casting we could recover the "Item" class from the "ListItem" class like this:

 

ListItem* ptr = list.front();

Item* item = (ListItem*)ptr;

 

However here, we have over-ruled the type system to enforce the cast from ListItem to Item. We need a way to perform this operation without breaking the type system rules.

 

 

 

 

One method is to store the type information in the base class, to be used later to reconstruct the derived class is, for example:

class ListItem {

public:

    bool isItem = false; // stored type information

    bool isLinkedItem = false;

}

 

class Item : public ListItem {

public: 

    Item(ListItem* listItem) {

        // reconstruct this class using p_list_item details    

    }

 

    // new method declared not accessible in ListItem class.

    void Print() {

        printf("item");

    }

}


ListItem* listItem = list.front();

if (listItem->isItem) {                           // check type information

    Item* item = new Item(listItem);              // reconstruct

    list.pop();

    delete listItem;                                  // delete old object

} else if (ptr->isLinkedItem) {

    // .etc

}


This is more desirable since the type system is preserved, which means that our code can be statically verified by the compiler. Also, it has an effect on how the classes are designed. Since now our type information is being manually specified, we can potentially perform more complicated operations depending on the base types-type members, for example:

if (listItem->isItem && !listItem->isLinked && listItem->isBack) { // reconstruct // }


The difference between class and object.

 The difference between class and object is subtle and misunderstood frequently. It is important to understand the difference in order to wr...