Search code examples
c++oopinheritancelinked-listvirtual-inheritance

C++ inheritance of linked list


class LinkedList{
    public:
    int data;
    LinkedList *next;
};

class NewLinkedList: public LinkedList{
    public:
    int data2;
};

When I use NewLinkedList, its next is still a pointer to LinkedList instead of NewLinkedList, so that I cannot access newlinkedlist.next->data2 without type casts. (newlinkedlist is an object of NewLinkedList.)

How can I design these two classes to avoid this problem?

Is there something like SELF_TYPE *next; and it becomes the type of derived class itself automatically when it is inherited?


Solution

  • You can use a template:

    template <typename T>
    class LinkedList{
    public:
        int data;
        T * next;
    };
    
    class NewLinkedList: public LinkedList<NewLinkedList>{
    public:
        int data2;
    };
    

    This technique is known as the Curiously recurring template pattern (CRTP)

    To improve the design, your LinkedList class should not contain any data other than what is needed for the linked list mechanism : it should be a base class only. Then you subclass it as above with specialized classes.