I'm declaring a 2-D dynamic array of Base class. Some of these dynamic objects are being declared as objects of Derived class. The constructor of the Derived class is being called on, but the object of Derived class is not calling on the correct virtual function
Organism is Base class Ant is Derived class
Organism.cpp
Organism::Organism(){//default constructor
occupy = false;
mark = '_';
}
Organism::Organism(int){//constructor called on by the Ant constructor
occupy = true;
}
char Organism::getMark(){//Used to make sure the Ant constructor is properly called
return mark;
}
virtual void yell(){//virtual function
cout << "organism" << endl;
}
Ants.cpp
Ant::Ant() : Organism(){}//not really used
Ant::Ant(int) : Organism(5){//initialize the Ant object
setMark('O');//mark
antsNum++;
}
void yell(){//override the virtual function
cout << "ant" << endl;
}
main.cpp
Organism **grid = new Organism*[20];
char c;
ifstream input("data.txt");//file contains data
for (int i = 0; i < 20; i++){
grid[i] = new Organism[20];//initialize the 2d array
for (int j = 0; j < 20; j++){
input >> c;//the file has *, X, O as marks
if (c == '*'){
grid[i][j] = Organism();//call on the default constructor to mark it as _
}
else if (c == 'X'){
grid[i][j] = Doodle(5);
}
else if (c == 'O'){
grid[i][j] = Ant(5);
}
}
}
//out of the loop
cout << grid[1][0].getMark() << endl;//outputs 'O', meaning it called on the ant constructor
grid[1][0].yell();//outputs organism, it is not calling on the Ant definition of the function yell()
I do understand that all the array is of type Organism, not of type Ant, how do I change that?