#include <iostream>
usingnamespace std;
class Base {
public:
Base() { };
virtualvoid print() { cout<<"Base\n"; };
};
class A : public Base {
public:
A() { };
void print() { cout<<"A\n"; };
void funInA() { };
};
class B : public Base {
public:
B() { };
void print() { cout<<"B\n"; };
void funInB() { };
};
int main() {
Base* arrayOfBasePointers[10] = {};
for (int i = 0; i < 5; i++) {
arrayOfBasePointers[i] = new A;
arrayOfBasePointers[i+5] = new B;
} //[0]..[4] is of type A, [5]..[9] is of type B
for (int i = 0; i < 10; i++) {
arrayOfBasePointers[i]->print();
} // this outputs nicely, A A A A A B B B B B
// arrayOfBasePointers[3]->funInA(); //error
// arrayOfBasePointers[8]->funInB(); //error
// Question! How do you make it works?
// I have tried this
((A*)arrayOfBasePointers[3])->funInA(); //OK
((A*)arrayOfBasePointers[8])->funInA(); //NOT supposes to be OK
// and this
A* arrayOfAObjects[5] = {};
B* arrayOfBObjects[5] = {};
for (int i = 0; i < 5; i++) {
arrayOfAObjects[i] = (A*)arrayOfBasePointers[i];
arrayOfBObjects[i] = (B*)arrayOfBasePointers[i+5];
}
arrayOfAObjects[3]->funInA(); //OK
arrayOfBObjects[3]->funInB(); //OK
//but then I cannot have a good feature like
//for (int i = 0; i < 10; i++) {
// arrayOfBasePointers[i]->print();
//}
}
At the end of the day, I ended up having both arrayOfAObjects and arrayOfBasePointers pointing to the same object. If I delete either one, the other one will have memory access violation, which I think is not a good way to achieve my goal.
Yes thank you. This will be a quick fix but in a long run, class A or B may have new functions being implemented while the Base class is not always available for amendment (i.e. adding in new virtual functions).