+ 1
Derived class is always pointed from base class?
Hi! I'm quite new to C++. I'm wandering whv derived class is pointed from base class in example like below? // Enemy is base class and have virtual function Ninja n; Monster m; Enemy *e1 = &n; Enemy *e2 = &m; Thank you in advance.
2 Respuestas
+ 1
This is called polymorphism (subtyping in this case), and allows the variables of pointer or reference to base class type to point or refer to derived classes, so you basically have a variable that can hold different types. Its like unions but restricted to only hold subclasses (and is safer in a way).
Virtual functions help pointers and references to a base class know which function to call by using some table of virtual function pointers known as the vtable.
Examples:
// Hero class can fight any enemy without needing to overload the member function
// for each enemy
void Hero::fight(Enemy* enemy)
{
// might want to check if it's not nullptr or just use a reference
enemy->take_damage(dmg);
}
// Vector of polymorphic types
vector<Enemy*> enemy_list;
enemy_list.push_back(new Monster());
enemy_list.push_back(new Ninja());
0
Hi jtrh,
Thank you for your clarification!
Now I understood it and could implement sample code.