Почему вызывается метод базового класса showConsol
, если при создании объекта мы явно указываем дочерний класс Gorod *obj2 = new Gorod
?
class Mesto {
private:
int coord_x;
int coord_y;
string name;
public:
static int count;
Mesto(int coord_x, int coord_y, string name) {
this->coord_x = coord_x;
this->coord_y = coord_y;
this->name = name;
count++;
}
int getCoord_X() {
return coord_x;
}
int getCoord_Y() {
return coord_y;
}
string getName() {
return name;
}
void setCoord(int coord_x, int coord_y) {
this->coord_x = coord_x;
this->coord_y = coord_y;
this->name = name;
}
void showConsol() {
cout << "Вызывается метод базового класса" << endl;
cout << "(" << name << ")" << endl;
cout << "Координаты, X: " << coord_x << " Y: " << coord_y << endl;
}
};
int Mesto :: count = 0;
class Gorod :public Mesto {
private:
int naselenie;
public:
Gorod(int naselenie, int coord_x, int coord_y, string name) :Mesto(coord_x,coord_y, name) {
this->naselenie = naselenie;
}
int getName() {
return naselenie;
}
void setName(int naselenie) {
this->naselenie = naselenie;
}
void showConsol() {
cout << "Численность населения: " << naselenie << endl;
Mesto::showConsol();
}
};
class MyList {
private:
struct MyElement {
Mesto *obj;
MyElement *next;
};
MyElement *head;
public:
MyList() {
head = NULL;
}
void addList(Mesto *bufobj) {
MyElement *temp = new MyElement;
temp->obj = bufobj;
temp->next = head;
head = temp;
}
void printConsol() {
MyElement *temp = head;
while (temp != NULL)
{
temp->obj->showConsol();
cout << "\n-------------------------------" << endl;
temp = temp->next;
}
}
~MyList() {
while (head != NULL)
{
MyElement *temp = head->next;
delete head;
head = temp;
}
}
};
int main() {
setlocale(LC_ALL, "RU");
MyList *list = new MyList();
Mesto *obj1 = new Mesto(1232, 2323, "Безымянное место");
Gorod *obj2 = new Gorod(123000, 2312312, -34534534, "Минск");
list->addList(obj1);
list->addList(obj2);
list->printConsol();
list->~MyList();
}