c++ - Class constructor being called twice -


i have written following code, , can't understand why enemy() constructor called twice. side question ask whether overriding member functions making them virtual , writing definitions again "correct" way of overriding functions between classes.

#include <iostream> using namespace std;  class enemy {     public: enemy();     virtual void attack(); };  enemy::enemy() {     cout << "\nenemy created";  }  void enemy::attack() {     cout << "\nattack inflicts 10 damage";  }  class boss: public enemy {     public: boss();     virtual void attack(); };  boss::boss() {     cout << "\nyou encounter boss"; } void boss::attack() {     cout << "\nattack inflicts 30 damage"; }  int main() {     enemy enemy1;     enemy1.attack();     boss boss1;     boss1.attack();     return 0; } 

i can't understand why enemy() constructor called twice

because inherits it, boss of type enemy. when construct boss, both constructor of boss , of enemy invoked.

// redacted lines aren't important. enemy enemy1; boss boss1; 

the above 2 lines creating 2 instances of type enemy. 1 of them happens bit more enemy, it's boss. it's still enemy, , therefore constructor of enemy invoked both objects.

i ask whether overriding member functions making them virtual , writing definitions again "correct" way of overriding functions between classes.

yes, is.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -