Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a class to provide Lists interface

Tags:

c++

list

class

Im trying to make a class to use in a Library, and im not sure if its even possible to do. The idea of this class, is to provide methods to insert, search and delete items on a list, but my main problem is that, as i dont know the type of object that i want to place in a list, I dont know how to work with it. I thought I could place a void pointer, and then make it point to a structure, but I havent been able to make it work.

Lets suppose my class is something like this:

class ListManager
{
    private:
         void* FirstItem;//This would point to the first item of the list
         void* LastItem;//This would point to the last item of the list
    public:
         void AddItemToList(void* Item);
         void RemoveItemFromList(void* Item);
}

So, the idea would be that, from my program, I can define a structure like

struct Employee
{
    *char Name;
    int Id;
    int PhoneNumber;
}

And then, use this class, to be able to add/delete Employees. So in this case, the void* pointers, should be pointing to a struct of the type Employee. Nevertheless, i want to make my class work for any type of struct. I dont know if i explained exactly what I want to do, I tried several ways of doing this, and failed on all of them.

Im going to post a code of how I would like the class to work, if I havent explained myself correctly

ListManager *Worker;
Worker=new(ListManager);

Employee *Item;
Item=new (Employee);

Item->Id=126;
Item->PhoneNumber=42154872;

Worker->AddItemToList(Item);
/*At this point, FirstItem and LastItem should point to the Item i just created*/

Could someone point me in the right direction, as how to make a class work with a structure, without knowing the type of structure?

Thanks in advance

like image 454
user2946417 Avatar asked Jan 21 '26 06:01

user2946417


1 Answers

You need templates! here's a simple interface that you can start working with.

template <typename T>
class ListManager
{
    public:
         void addItemToList(const T& item);
         void removeItemFromList(const T& item);
}

Now T is your type, and you'd declare a ListManager like this:

ListManager<Employee> manager;

I would suggest you also to look at the stl documentation/implementation of a list at: http://www.cplusplus.com/reference/list/list/ You have also the concept of iterators to dig into. Also, try to use values instead of pointers. With the interface I gave you, you would store the actual value in the list and not a pointer, so the list owns the object and you won't need to manage your memory manually.

like image 52
dau_sama Avatar answered Jan 23 '26 20:01

dau_sama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!