I am trying to create a BaseClass array that stores SubClass objects. Below are the follow steps I use to do this:
- I create a BaseClass array.
- I create a new SubClass object to be stored in the array.
- I call the printSelf() function of that object in the array.
- The method incorrectly calls the BaseClass function, not the SubClass function.
The error here is that the object stored in the BaseClass array is of a BaseClass object. I need it so that the BaseClass array stores an object of type SubClass.
The problem is designed such that if there were to be multiple SubClasses (i.e. SubClassA, SubClassB, SubClassC...) they would all be stored in a single array.
I've tried various other solutions on StackOverFlow. None so far have provided a solution as to why creating a SubClass object will not store its class type properly in a BaseClass array.
class BaseClass {
public: void printSelf() { cout << "This element is a BaseClass." << endl; };
};
class SubClass : public BaseClass {
public: void printSelf() { cout << "This element is a SubClass." << endl; };
};
class House {
public: House();
private: BaseClass* subClassArray[1];
};
House::House() {
subClassArray[0] = new SubClass;
subClassArray[0]->printSelf();
}
int main() {
House houseMain;
}
I expect the output to be "This element is a SubClass."
Instead, the output I am receiving is "This element is a BaseClass."