Hi, I'm working on a project and it's in a stage that I don't know what's wrong. Here's the simplified version:
The code:
class Base { // This base class is pure abstract
public:
virtual ~Base(); // Necessary to trigger destructors in inherited classes
virtual baseFunc() = 0;
};
class DerivedA : public Base{
public:
DerivedA(SomeClassUseBase * tmp){
tmp -> register(this);
}
~DerivedA();
void baseFunc(){
// do something here that's only for DerivedA
}
};
class DerivedB : public Base{
public:
DerivedB(SomeClassUseBase * tmp) {
tmp -> register(this);
}
~DeriveB();
void baseFunc(){
// do something here that's only for DerivedB
}
};
class SomeClassUseBase {
private:
Base ** basePrt;
unsigned int index;
public:
someClassUseBase(int num) {
basePrt = new Base*[num]; //create an array of pointers to the objects
index = 0;
}
void register( Base * base ){
//i tried *(basePrt[index]) = *base, but got the same problem
basePrt[index] = base;
index = index + 1;
}
void checkList() {
for (int i = 0; i < index ;i++){
next = basePrt[i];
next -> baseFunc(); //fails here
}
}
};
int main() {
SomeClassUseBase tmp = new SomeClassUseBase(5);
Base *b[5];
for ( i = 0; i < 5; i += 1 ) {
if ( i % 2 == 0 ) {
b[i] = new DerivedA(&tmp);
}
else {
b[i] = new DerivedB(&tmp);
// the object pointed by tmp::basePrt[0] is lost after this line
} // if
} // for
tmp.checkList(); //crashes here since tmp.bastPrt[0] points to null
}
The problem is that when in main, i reach the line when the first DerivedB is created, the already created DerivedA pointer by tmp.basePrt[0] is lost some how. I don't know why but i suspect that this has sth to do with polymorphism? Please help!! thanks!!
Edit:
Didn't quite get the code correct the first time, sorry...