c++ - Create a linked list using base a class and a derived class -


how can create linked list using base class , derived class

eg.:

class base {      int id;     base *next; }; class derived : public base {     string name; };    base *list = null;  base *b = new base(); b->next = list; list = b;  derived *d = new derived(); d->next = list; list = d;  base *itr = list; while(itr) {     if(typeid(base) == typeid(*itr)) {         cout << "base: " << itr->id << endl;     } else {         cout << "derived: " << itr->id << " , " << itr->name << endl;     }     itr = itr->next; } 

my approach not work! suggestions?

what want works fine. see complete example:

#include <stdio.h> #include <typeinfo>  struct base {     base *next; int id;     base(int id) : id(id) {}     virtual ~base() {} };  struct derived : base {     int id2;     derived(int id, int id2) : base(id), id2(id2) {} };  void link(base *n, base **list) {     n->next = *list; *list = n; }  int main(int argc, const char *argv[]) {     base *list = 0;     link(new base(10), &list);     link(new derived(20, 21), &list);     link(new base(30), &list);     link(new derived(40, 41), &list);      (base *p = list; p; p=p->next) {         if (typeid(*p) == typeid(base))             printf("base(%i)\n", p->id);         else             printf("derived(%i, %i)\n", p->id, ((derived *)p)->id2);     }     return 0; } 

however must have @ least 1 virtual member typeid work.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -