After playing around with linked lists I wanted to suss out how to add derived classes into a linked list. I found it was much easier to create the object class using "new" and push the pointer to the object onto the list.
Here's a working example of a 2d editor which I'm going to be working on.
"Main.cpp"
#include "DarkGDK.h"
using namespace std;
#include <list>
#include "drawings.h"
void DarkGDK ( void )
{
dbSyncOn ( );
dbSyncRate ( 60 );
// create my drawings list
db_list mydb;
// add some stuff to my list
mydb.add_ink(0xffff00);
mydb.add_box(50,50,100,100);
mydb.add_ink(0xffffff);
mydb.add_circle(100,100,100);
mydb.add_box(100,100,140,200);
mydb.add_ink(0x00ffff);
mydb.add_circle(120,120,30);
mydb.add_circle(120,120,32);
while ( LoopGDK ( ) )
{
// draw some stuff using normal commands
dbInk(0xffffff,0);
dbBox(0,0,50,50);
dbInk(0xff0000,0);
dbBox(10,10,40,40);
// draw all the objects in the list
mydb.draw();
dbSync ( );
}
return;
}
"drawings.h"
class db {
public:
// declare a function used in all derived classes
virtual void draw() const = 0;
};
class db_box: public db {
public:
int x1,y1,x2,y2;
void draw() const {
dbBox(x1,y1,x2,y2);
}
void set(int newx1, int newy1, int newx2, int newy2) {
x1=newx1; y1=newy1; x2=newx2; y2=newy2;
}
};
class db_circle: public db {
public:
int x1,y1,r;
void draw() const {
dbCircle(x1,y1,r);
}
void set(int newx1, int newy1, int radius) {
x1=newx1; y1=newy1; r=radius;
}
};
class db_ink: public db {
public:
int col;
void draw() const {
dbInk(col,0);
}
void set(int c) {
col=c;
}
};
// ## List handler ##
class db_list {
list<db*> lst;
list<db*>::iterator itr;
public:
void add_box(int newx1,int newy1,int newx2,int newy2) {
db_box* box=new db_box;
box->set(newx1,newy1,newx2,newy2);
lst.push_back(box);
}
void add_circle(int newx1,int newy1,int radius) {
db_circle* circ=new db_circle;
circ->set(newx1,newy1,radius);
lst.push_back(circ);
}
void draw() {
for (itr=lst.begin(); itr!=lst.end(); ++itr) {
db* obj=*itr;
obj->draw();
}
}
void add_ink(int c) {
db_ink* ink=new db_ink;
ink->set(c);
lst.push_back(ink);
}
};
I hope this helps understanding derived classes and adding them to a list.
Warning! May contain Nuts!