I tried to implement multi-data list with a reference instead of
pointer to data, but code compiled with gcc perform "segmentation
fault". Generated code from other compilers: Borland C++ 5.0 and
Micros. C++ 6.0 is OK. What is wrong?
#include <iostream>
using namespace::std;
class base {
public:
virtual void dump() = 0;
};
class chr : public base {
char ch;
public:
chr(char s) { ch = s; }
~chr() { }
void dump() { cout << ch ; }
};
class num : public base {
int n;
public:
num(int i) {n = i; }
~num() {}
void dump() { cout << n; }
};
struct node {
base &data;
node *next;
node(base &d) : data(d) {}
};
class list {
node *n;
public:
list() : n(0) {}
void add(base &d);
void dump() {
for(node *tmp = n; tmp; tmp = tmp->next)
/* THIS IS LINE WHERE SEGMENTATION OCCURS */
tmp->data.dump();
}
};
void list::add(base &d)
{
node *tmp = n;
if (!n) {
n = new node(d);