Generic Linked List in C++

I've been trying to figure out how to implement a generic linked list and this site has been wonders but i'm up to this point which has seemed to have worked for other users although they couldve been working on it years ago i didnt check the time stamps. It causes a compile error which is error: ‘class node_base’ has no member named ‘data’ but if node is inheriting from class node_base it shouldnt need to have a member named data. Ok so i can see why node_base would need a member named data since n is of type data i'm wondering if i cast upwards with a dynamic cast if that would solve this issue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class node_base {
   node_base* next;
public:
   node_base() : next() {}
};

template<class T>
class node : public node_base {
   T data;
public:
   node(const T& d) : data(d) {}
};

class polymorphic_list {
   node_base* head;
public:
   polymorphic_list() : head() {}

   template<typename T>
   void insert(const T& d){
      node_base* n = new node<T>(d);
      n->data = d;
   }
};
Last edited on
It causes a compile error which is error: ‘class node_base’ has no member named ‘data’ but if node is inheriting from class node_base it shouldnt need to have a member named data.


That says that ‘class node_base’ has no member called data - which is obviously true.
So this line here:
n->data = d; causes the error.

using a base class pointer to point to a derived class does not allow you to access the
member variables of the derived class. member variables are not polymorphic.

P.S the n->data = d; line is redundant anyway.
Keep in mind that the post the above code was taken from was an academic solution to a polymorphic list
problem. A polymorphic list is a list that can contain non-homogenous elements, and is not necessarily
the same thing as a "generic linked list", which to me implies a list that can support any type, but only one
at a time, a la the STL containers.

Only the first solution of the three I gave in my reply seems to have any merit in a real-world application;
the other two essentially do not provide an easy, efficient means by which elements can be retrieved
from the list by the user.

Perhaps we should ask what you are really trying to accomplish.

Iv created a SmartPtr class that i believe works but i want to store each smart pointer in a linked list originally i wanted to store a reference to each memory address then i could sort the list and find out how many Smart pointers were pointing to the same object but i couldnt figure out how to do that in the constructer and i got errors that saw the reference as a class*& instead of int*& or int&
Can't you just use boost's smart_ptr library along with STL lists/vectors instead of reinventing them?
Topic archived. No new replies allowed.