Bugmaker Bugmaker - 3 months ago 11
C++ Question

List inheritance in C++

I'm doing a program that involve a lot of lists of multiple class. I'm pretty sure it has a name but I don't really know how to call it, what I would like to do is to make a common list which contain some functions (like element insertion, getter...) which all lists inherit and can use functions of the common list. So my question is how to do it with an example if possible.
I've made a header code example below.

class CommonList {
public:
// Add some functions
// T here is not a class I've made.
void insere(T element);
T getElement(int id);
protected:
std::map<int,T> m_map;
};

class A {
public: A();
}

class B {
public: B();
}

class ListA : public CommonList {
// Tell the program that element T are ONLY object of class A.
// Like if I would have made this.
/*
public:
void insere(A element);
A getElement(int id);
protected:
std::map<int,A> m_map;
*/
};

class ListB : public CommonList {
// Same for B.
}

Answer

I'm pretty sure it has a name but I don't really know how to call it

The word you are looking for is a template class.

And this is how it is being done:

template <typename T>
class CommonList {
public:
    void insert(T element){
        /* Implement your insert function here */
    };
    T getElement(int id){
        /* Implement your getElement function here */
    };
protected:
    std::map<int,T> m_map;
};

And then you can simply create any type of that list, for example:

int main(){
    CommonList<int> int_list;
    my_list.insert(7);
    CommonList<double> double_list;
    my_list.insert(4.3);
}

You may of course also inherit from this class to and override the functions as you wish.

class A{}; 
class ListA : public CommonList<A>{
    // ... 
};

Or as a template

template <typename T>
class ListT : public CommonList<T>{
    // ...
};

See Templates Topic in Documentation for more details and examples.

Comments