Hi, im trying to write a simple virtual function that a base object;s derived objects can use. But i seem to keep running into problems, firstly:
I have an object called LatticeNode which stores the object (cell or its derived type). This class also has a function called getCell which returns a reference to this object. Ill try to explain my code a little before i ask the questions.
Eg. The LatticeNode class is:
Code:
class LatticeNode {
public:
int num;
Cell *t;
void set(int i, int j);
void setI(int x) { i = x; }
void setJ(int x) { j = x; }
void setNum(int i) { num = i; }
void inc();
void dec();
void inc_i() { i++; }
void inc_j() { j++; }
LatticeNode *next;
LatticeNode *prev;
Cell* getCell();
//default constructor
LatticeNode(Cell *c);
LatticeNode();
int getI() { return i; }
int getJ() { return j; }
int getNum() { return num; }
private:
int i;
int j;
};
the getCell function is defined as this (with the constructor - this may be wrong also):
Code:
LatticeNode::LatticeNode(Cell *c)
{
num = NULL;
next = NULL;
prev = NULL;
t = c;
}
Cell* LatticeNode::getCell()
{
cout << "In get cell" << endl;
if(typeid( t ).name() == "Class Cell *")
return (Cell *)t;
if(typeid( t ).name() == "Class Juxtacrine *")
return (Juxtacrine *)t;
if(typeid( t ).name() == "Class Morphogen *")
return (Morphogen *)t;
return t;
}
Now ignore the typeid if statements, and look at the constructor. Am i getting this assignment correct? the t = c;?
Does this assign the Cell object (or its derived type) to t? Ive checked at runtime and it seems to assign to the correct type, although im not sure...
In the getCell function do i just need to do a return t; ? instead of all this typeid stuff? polymorphism would suggest i dont as it should return the correct object type even if its derived?
Ive been using this code to try and test the getCell function but all i get are Cell * types back.
Code:
Morphogen *a = new Morphogen();
Juxtacrine *b = new Juxtacrine();
LatticeNode *n = new LatticeNode(a);
LatticeNode *m = new LatticeNode(b);
cout << typeid( n->getCell() ).name() << endl;
cout << typeid( m->getCell() ).name() << endl;
in the cout statements all i get is "Class Cell *"
Should i be getting "Class Morphogen *" etc? or am i doing something wrong?
I am also trying to get a virtual function to work with this object hierarcy but if i try to call it i get an exception?? eg
Code:
class Cell
{
public:
virtual void print() { cout << "im a cell" << endl; }
};
class M : public Cell
{
public:
void print() { cout << "M"<< endl; }
};
class J : public Cell
{
public:
void print() { cout << "J"<< endl; }
};
}
when i call print() i get an exception if i use the getCell method to call it eg:
LatticeNode *n; n->getCell()->print();
Any ideas? as this is causing me loads of problems...!