c++ - Calling Non Virtual Method from child class -
i know based on polymorphism cannot call non virtual function/method
ex:
class entity { public: entity() { health = 10; } void displayhealth() { std::cout << health << std::endl; } protected: int health; }; class player : public entity { }; class enemy : public entity { void sethealth(int n) { health = n; } }; int main() { entity *instance = new enemy(); instance->sethealth(1); // error return 0; }
so have come counteract this:
int main() { entity *instance = new enemy(); enemy e = *(enemy*)instance; e.sethealth(1); instance = &e; }
this works fine needs i'm wondering if "correct" way of doing it. there more efficient way call child class method using polymorphism?
entity *instance = new enemy(); enemy e = *(enemy*)instance;
creates new enemy object , assigns pointed instance it. redundant. , then
instance = &e;
causes memory leak because lost pointer new enemy()
, have not deleted it.
int main() { entity *instance = new enemy(); enemy *e = static_cast<enemy*>(instance); ^^ e->sethealth(1); }
==================================================================================
==================================================================================
however seeing health
member of base class entity
, can move sethealth
function entity , done it.
class entity { public: entity() { health = 10; } void displayhealth() { std::cout << health << std::endl; } void sethealth(int n) { health = n; } protected: int health; }; int main() { entity *instance = new enemy(); instance->sethealth(1); // not error anymore return 0; }
Comments
Post a Comment