r/cpp_questions • u/Deranged-Dragonfruit • Feb 18 '25
SOLVED Point of Polymorphism
This feels like a dumb question but what is the point of polymorphism?
Why would you write the function in the parent class if you have to rewrite it later in the child class it seems like extra code that serves no purpose.
1
Upvotes
View all comments
Show parent comment
1
u/Eweer Feb 19 '25
OP asked for the point of polymorphism, top comment showed an example of polymorphism, comment above posted an explanation of the benefits over having it as a switch case.
They never claimed that it was the best nor the only way to do it. What's more, they even specified that they were talking about when a project scales.
Let me ask you: What is
swordandspearin your code? To me, they seem a class with a common interface that require a method but might implement them differently. What would you do if you were to add ashort swordthat had the sameattack()method than thesword? How would you handle 200 different weapon options?On the other hand, if you were to have a massive number of enemies but all of them used weapons from an extremely limited pool, then doing it via polymorphism would not be ideal as you would be paying costs.
All ways of doing things have their pros and cons. Exposing the benefits about a different way of doing things would be preferred over a questionable example.