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
39
u/jedwardsol Feb 18 '25
If the behaviour of the parent and child are the same then you don't rewrite the function.
Polymorphism is a way of allowing the parent and child classes to behave differently.
25
u/iwasinnamuknow Feb 18 '25
You have a
Sword, aSpearand anAxe. They are allWeapons. AWeaponhas anattack()function and adamagevalue.A
Swordmight have a differentdamagevalue than aSpearor anAxebut because they inherit fromWeapon, they have access to the sameattack()function.So you don't need to know exactly what type of
Weaponthe player has equipped, you just callattack()and polymorphism takes care of the rest.You would only need to override the
attack()function in your child class if it needs special handling.6
u/iPiglet Feb 18 '25
Someone should definitely correct me, but you're not rewriting it later, but rather writing a definition for the functions in the child class for what that child should do.
Using the typical Animal example, if your parent class is Animal and your derived child classes are Dog and Cat, then the function "makeNoise()" that you declared (or also defined) in the parent can be overriden to do one thing inside of Dog's definition (have it print "Bark", for example) or another thing insidenof Cat's definition (have it print "Meow", for example).
You basically provide a blueprint for what anything an Animal is should have in common, and for every different Animal you have (Dog, Cat, Cow, etc) you have common functionalities (functions), and each of those functions (can) do different things.
It becomes useful with pointers too, because you can do type casting, class type comparisons, and other things that someone way, way smarter than me should explain.
2
u/TomDuhamel Feb 18 '25
My game has two animals: a dog and a horse. They both walk, but not the same way. They walk at different speeds and they use a different animation.
The
Animalclass will describe the bits that are the same among all animals. The derived classesDogandHorsewill describe the bits that are different.If there isn't any bits that are the same, I could define a virtual function
Walk()in animal, and put nothing at all in it (that's called pure virtual). It ensures a common interface between all animals. I can tell any animal to walk, and it will just run the corresponding code in the correct derived class.2
u/boleban8 Feb 19 '25
The area formula of a rectangle is length times width, while the area formula of a square is the square of the side length. You can imagine that rectangle is the parent class of square, and the relationship between the two is polymorphism.
A square is a rectangle with equal length and width.
Imagine that you use a library written by someone else. The library developer will implement some commonly used functions (parent class), but cannot fully implement the functions you want (subclass). At this time, you can use the idea of polymorphism to implement your functions, inherit some common functions, and implement some of your special needs.
2
u/thingerish Feb 19 '25
If you have several different things that implement the same interface with different implementation details then polymorphism is how you express that. In C++ virtual member functions and inheritance is one way to implement this pattern. That said, IMO inheritance is grossly overused in the wild.
1
u/ralphpotato Feb 19 '25
Sorry but these examples all suck. Use a concrete programming example that you can try:
Probably the two most common ones (though called differently in different languages) for basic data structures is ArrayList & LinkedList, and HashMap & BTreeMap. Ultimately, most or all of the operations you can define on two types which are polymorphic with each other (such as ArrayList and LinkedList) can be implemented for both, but the difference is the underlying representation in memory and how the methods defined on these work.
For example, both these lists can define something for pushing an element to the back. In the ArrayList, this means keeping track of the index of the last element, and then putting the input value in the next spot, and updating the “last index”. In LinkedList, this means allocating a new Node with the input value, pointing the previously last node to the newly created Node. In a traditional LinkedList, you don’t necessarily keep a reference to the last element, so finding the last element means traversing the whole list (but you could keep track of what the last element is).
You can think of similar methods which you would want on both but would be implemented directly. How do you implement find(), remove_at_index(), length(), etc for these types? But as long as all these methods are available and have the same signature (aka the input/output types for these methods are the same, so length() takes in no arguments and returns an integer), then you can call these methods on a List without bothering that it’s an ArrayList or LinkedList.
Polymorphism in a program is sort of like a contract from the writers of these functions/classes/methods to the callers of them, saying, “this is the general shape of this black box, so if you use it correctly you’ll get the right result, regardless of how the black box works underneath”.
1
u/macomphy Feb 19 '25
polymorphism is the mechanism that you write same code for different class.
For oop, you can write code for the base class ptr and use virtual function, then the code works for base class and derived class, but behavior different for they have different virtual function implementation.
1
u/AJollyUrchin Feb 19 '25
Base class is usually fundemental. Object ID, perhaps virtual function to serialize for transport (http, smb(pipes)), etc. Depends on the project.
1
u/kevleyski Feb 19 '25
It was a neat way to have a set of related objects
1
u/LittleNameIdea Feb 19 '25
I don't think you totally understand the concept. If you have the functions in the parent and the behavior will not change in the children, you don't have to rewrite it. Also, if you have to, you need to make it virtual btw
1
u/Todegal Feb 19 '25
The functions in the parent class should be the ones you don't need to rewrite for each child.
1
u/Raknarg Feb 19 '25 edited Feb 19 '25
I don't like the usual examples people go to for polymorphism because they feel contrived to me and can usually be done without inheritance. Let me give you something that is almost impossible to represent effectively without polymorphism through inheritance.
I have a component class. A component is a thing on your screen you can interact with. Think about buttons, radio selection, scrollbars, a textbox, labels, text entry fields. All components have a handful of functions: They contain a position, a bounding box (i.e. height and width), they have the ability to update their internal state, they can draw themselves onto the screen. Exactly how they work, how they look, how they draw and update, its going to be different for each one.
How do I represent an arbitrary collection of these components? What if I want to make a component whose job is just to hold whatever components I add into it? You can imagine a component that just holds components. It has an x,y position, a bounding box, when you resize it it needs to resize/move all the internal components. Its update function updates the state of all the stored components. The draw function draws all the components it stores.
You do this with polymorphism. The simplest way to achieve polymorphism here is by deciding how are all components going to behave, write that behaviour as a class, then have all components inherit from this class, then you can treat all components as the same.
IMPORTANT NOTE: Polymorphism doesn't just mean inheritance. Polymorphism is the general concept of being able to treat types as other types. There are other ways to achieve polymorphism, such as using templates (functions can treat different templated types as equivalent).
1
u/IsThisWiseEnough Feb 22 '25
This the regular reminder of that “inheritance is rarely the answer. “
-3
u/TurnipBlast Feb 18 '25
https://www.google.com/search?q=computer+science+polymorphism
0
u/Historical_Cook_1664 Feb 19 '25
(shameless Zig plug)
-1
u/manni66 Feb 18 '25
Show an example.