+ 2
[CLOSED] Does Polymorphism Require Pointers?
I've been looking at many examples of polymorphism and most of them make use of pointers. But a few people said in the comments how the pointers are pointless (haha funny joke). It appears you have to use pointers for correct polymorphism but I want to make sure... Example in the lesson: #include <iostream> using namespace std; class Enemy { public: virtual void attack() { } }; class Ninja: public Enemy { public: void attack() { cout << "Ninja!"<<endl; } }; class Monster: public Enemy { public: void attack() { cout << "Monster!"<<endl; } }; int main() { Ninja n; Monster m; Enemy *e1 = &n; Enemy *e2 = &m; e1->attack(); e2->attack(); }
3 Respostas
+ 5
First of all, there is not only one type of polymorphism. You usually distinct between static and dynamic polymorphism:
https://www.quora.com/How-many-polymorphism-types-does-C++-have
I think the comments are referring to the fact that in this case, the main function could also be written like this:
Ninja n; n.attack();
Monster m; m.attack();
So no, inside your code, pointers are neither necessary for the correct method to be called, nor are they mandatory for polymorphism.
Why use pointers then? A better example would be where you have loads of enemies, which you will want to store in an array, obviously. The problem is the array must be of a single type, so cramming ninjas and monsters alike into one won't work. What will work, however, is an array of pointers to enemies. What the pointers point to doesn't matter, and you can happily iterate over the array and call attack() on each enemy without having to worry about whether the correct method is called.
+ 3
Without pointers, there can't be Polymorphism....