0

I'm working with Lists using C++ and I had a little doubt. Each Cell have a pointer to next cell and your data. Now each cell is using the class Data1.

class Data1
{
    public:
        int item1;
};

class Data2
{
    public:
        int item2;
};

class List
{

    /* Each cell of list */
    typedef class Cell
    {
        public:
            class Data1 data;
            class Cell *next;

    }Cell;
    .
    .
    .
}

How can I generic it to use Data1 or Data2 for diferent applications?

A better explaination is if Data2 are on another source code and the Cell point to Data2 not Data1.

Thank you!

marquesm91
  • 535
  • 6
  • 23

1 Answers1

0

You can use templates for this:

template<class Data>
class List
{
    struct Cell { Data data; Cell* next; };
};

At instantiation time you can pass the intended class to be used as the type of data:

List<Data1> list1;
List<Data2> list2;

Also, you don't need the prefix class or struct when defining instances of classes in C++.

iavr
  • 7,547
  • 1
  • 18
  • 53
David G
  • 94,763
  • 41
  • 167
  • 253
  • This helps a lot! I have one last question. I have created a main and incialize like you said: List list1; but when I try to compile this error insist: (...) undefined reference to List::List(). I picked the constructor for a example, but all my functions on list.cpp get this error. I know that the error is to link correctly but I don't know how to processed. – marquesm91 Sep 06 '14 at 20:01
  • @marquesm91 Since your class is a template, you need to keep the implementation of your constructors/functions/etc. inside the `.cpp` file. Read [this](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) for more information. – David G Sep 06 '14 at 20:08