# When to use polymorphism

This topic is 1505 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

In which cases I should use polymorphism ?

I know that if we create classes mammal, cat and a dog like:

class mammal
{
...
virtual void Run();
};

class cat : public mammal
{
...
Run();
};

class dog : public mammal
{
...
Run();
};

void main()
{
mammal *pMammal1;
mammal *pMammal2;
cat *pCat = new cat();
dog *pDog = new dog();

pMammal1 = pCat;
pMammal2 = pDog;
}


we can access cat and dog trough mammal. But what is the use of this, when we can implement this ? Why not just put Run() inside cat and dog without having mammal ?

Edited by ryt

##### Share on other sites

How can you access this function??? I thought you need inheritance but there is nothing just three seperated classes...

you would need something like:

class mammel
{
public:
virtual void run();
};

class dog : public mammel
{
public:
virtual void run();
};

class cat : public mammel
{
public:
virtual void run();
};



but perhaps i am wrong and just learned it wrong.

With polymorphie you recive a behavior "similar" to an array/list of functionpointer which do there job everytime they are called but here instead of an array/list you have

the class herachie with overrided functions but in case you need an different behavior of an function which was overriden but you need the original with help of polymorphie you could access this function dynamically. // just a very hard simplification

Edited by exOfde

##### Share on other sites

Why not just put Run() inside cat and dog without having mammal ?

Because then you wouldn't be able to write code that just deals with mammal (i.e. doesn't care if something is a dog or a cat - thus the same code can apply to any Mammal).

##### Share on other sites

Lets say you want all your mammals to run, with polymorphism you can put all your mammals in a single mammal array and call their run function. Without polymorphism you'll have to keep a list of dogs, cats etc. and call their run function.

##### Share on other sites

How can you access this function??? I thought you need inheritance but there is nothing just three seperated classes...

Yea, I forgot to put public mammal. I fixed it now.

So polymorphism is similar to the use of interfaces. If I am not wrong interfaces are classes that contain methods that will be used in multiple other classes, like Run() method here ?

Edited by ryt

##### Share on other sites

Lets say you want all your mammals to run, with polymorphism you can put all your mammals in a single mammal array and call their run function. Without polymorphism you'll have to keep a list of dogs, cats etc. and call their run function.

IMHO being able to lazily throw all objects into a huge list to avoid having specialized lists is not sufficient reason for using virtual methods, because the specialized lists could directly store the objects, but the single list would be more complicated in some other way as it needs to store pointers and would necessitate many useless pointer indirections to separately allocated objects and virtual calls.

I think there needs to be some other reason to use virtual methods, for example, being able to hide some low level implementation details or interfacing with library code.

I dont really like the example with the mammal, dog and cat, because in a game the code for letting them run would probably be the same for all kinds of living things with legs and a single class could be used for them.

##### Share on other sites

How can you access this function??? I thought you need inheritance but there is nothing just three seperated classes...

Yea, I forgot to put public mammal. I fixed it now.

So polymorphism is similar to the use of interfaces. If I am not wrong interfaces are classes that contain methods that will be used in multiple other classes, like Run() method here ?

With an interface, every class has to define the method separately even if each has identical code. With a class, you have default behavior (unless you used a pure virtual function) that is only overridden when necessary. So you could have mammal::run() be the same code for every mammal like wintertime mentions, but you could have mammal::makeNoise() result in "meow" for a cat and "woof" for a dog. And if you had a weird mammal that runs differently, you could override run() just for that one mammal without needing to write run() code for every single type of mammal you have defined.

I agree with wintertime that you should not use polymorphism just to use it though, and it should be used when it is actually solving a problem that is otherwise difficult to solve.

##### Share on other sites

It's especially worth noting that run-time polymorphism is very much possible (and arguably cleaner!) without inheritance -- I strongly recommend watching this:

http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil

Actually Sean Parent's solution that you mention there does indeed use inheritance - it is just encased into an inner base class that is insulated from the user.  That's strictly a technicality though...

I tried this out to implement a form of a mixed object graph, and it works like a charm!  Type erasure for the win!

##### Share on other sites

One place where polymorphism is used to model "game objects" in simple games. Such games might have an abstract "Game Object" or "Entity" class, from which all objects in the game derive from. This might have a handful of virtual functions, such as one to advance the object's state by one frame, and another to draw the object. Much of the higher level code can be written in terms of these game objects, the exact type of which is irrelevant. From the game's point of view, a Kitten and a Space Marine are essentially the same, they both need to be moved every so often, and they both need to be displayed.

In complex games, such as AAA games, a simple model like the above is not used. One reason is the number of classes that would be required becomes too much. Another, is that handling object specific behaviour may be delegated to a script files that are loaded at runtime rather than compiled into the executable.

Another place I see people using polymorphism is for managing the main menu, settings, running game and pause screens, etc. A class might be created called "GameMode" or "GameState". A  concrete subclass could be created for a the MainMenu, PlayingGame, PauseScreen, and so forth. Much like the game objects, these might some virtual functions to update and render. They might also need functions to react to input events. Finally, a mechanism for transitioning to the next state is needed. One way to do this is to have the update() function return a smart pointer to the next mode or state, if a transition is to be made. If no transition is needed, then no pointer is returned.

This can sometimes be modelled as a simple GameMode/GameState enum, which dispatches to various state-specific functions, avoiding the need to create a class hierarchy.

In general, the more important thing is to know when to avoid polymorphism. Programmers who are not experienced in object oriented programming tend to over-use inheritance. While mostly harmless, in some cases misusing inheritance can degrade the code quality. In most games, there wouldn't be dedicated Cat and Dog classes. These game objects typically are quite similar for most intents and purposes, the differences are not in the actual game object behaviour but in their data.

Even a moderate sized game might instead have a general Animal class rather than specific sub-classes. The Animal class could take a variety of arguments to the constructor including what texture and meshes it should use, which sounds it will play and what speed and ferocity it has. This data can then be easily moved into a file, which the game loads. This would allow the game designer to quickly tweak how fast a cat runs, without needing to recompile the entire game executable. This flexibility would allow you to bring your game to play test at a friend's house, where when you realise during the test that cats are too slow and are not correctly balanced, you can change the value there and then and test that the new one is better.

A counter example might be if the game models the animals in such detail that each class would have unique behaviour, for example, a cat landing on their feet after a fall, but a dog would not. In this case, it may be preferable to have two classes to handle this, than to try treat this as data (e.g. a "will_land_on_feet_following_fall" boolean).

As you can see, there is no absolute right answer. Coming up with and evolving designs for these scenarios and more is a skill that you hone by making bigger and bigger games. What works for Pong will often not work for GTA XXVII, and overengineering the code for a simple game wastes lots of time that could be spent making the actual gameplay more fun, making better assets or recruiting artists, all of which would be more valuable to the player.

Edited by rip-off

##### Share on other sites

In which cases I should use polymorphism ?

When the behavior of the class must change at run-time.

If you know you will have dogs & cats then can keep a list of dogs separate from a list of cats.

If you know you will have dogs, cats, and "some other animals" then you need polymorphism. It is designed to handle that ambiguity.

The usage of polymorphism has evolved into an Interface / Implementation pairing. You design a completely abstract interface, which is a contract of what the implementation must do. It is more than function signatures, it is a set of guaranteed behavior. (This is not how you must or should use it, that's just how it is commonly done. C++ gives you some more choices.)

##### Share on other sites

One place where polymorphism is used to model "game objects" in simple games. Such games might have an abstract "Game Object" or "Entity" class, from which all objects in the game derive from. This might have a handful of virtual functions, such as one to advance the object's state by one frame, and another to draw the object. Much of the higher level code can be written in terms of these game objects, the exact type of which is irrelevant. From the game's point of view, a Kitten and a Space Marine are essentially the same, they both need to be moved every so often, and they both need to be displayed.

In complex games, such as AAA games, a simple model like the above is not used. One reason is the number of classes that would be required becomes too much. Another, is that handling object specific behaviour may be delegated to a script files that are loaded at runtime rather than compiled into the executable.

So I assume that AAA games use scripts to do some specific object behavior. But for those scripts I assume they would still use some objects ?

Unity 3D uses "Game Object". So does Unity 3D fall into this AAA ? I mean are there any games that are AAA and are built in it ?

##### Share on other sites

Polymorphism is used in order to treat a set of objects equally without regard to implementation details. Interfaces are used in order to treat a set of objects equally without regard to implementation details. The classic distinction being the Is-A/has-A relationship.

Someone mentioned that they don't like the Cat/Dog run example b/c they would both use the same logic... however, I'd like to point out that is exactly a good reason to use polymorphism over interfaces...

Instead of Mammal, imagine the base class is Animal. Now, your animal class has a virtual function run, implemented in such a way that the majority of animals share this logic... now cat and dog inherit from animal and neither require any further run implementation because Animal already handles it. However, you also decide to create a bird Animal... it has a bird specific Run implementation (It actually flies so it's choice of path can ignore factors cats/dogs can't). Polymorphism is good here because all animals can "Run" in some sense of the word.

I would be willing to bet that the majority of AAA games use Polymorphism at least to some extent, but *in addition* they also make great use of composition. Composition is the has-a relationship where a behavior is attached to the object rather than derived from a base class.

If you look at unity3D, game objects are little more than an object to which behaviors can be attached, but those behaviors are derived from a base class, meaning each game object implements both composition and polymorphism to achieve the end result of being usable unit of code.

##### Share on other sites

You might need polymorphism when you need to do the same operation to multiple types of objects.

However, polymorphism is not the only possible solution. You can go lower level and use something like function pointers instead (which might or might not come with lower overhead depending on implementation). You can also use external code to decide what should be done based on object type (eg. you could have a void* pointer associated with a type enum) using a switch or a pile of if statements.

Polymorphism is just syntax to simplify the usage of one of the above options, which hides some details and thus is more flexible in many cases. However, sometimes it makes sense to use one of the alternatives for performance reasons. This is because the compiler specific implementation of the virtual polymorphism "built in" to the language is likely to lack some of the knowledge you as a programmer have about the code, and thus will have to be general. Or perhaps the implementors decided not to cover every special case for simplicity and compilation speed or whatnot.

In other words, the built in polymorphism through virtual methods will always be able to handle the task, but more low level or specific approaches might be more desirable if you know your requirements.

##### Share on other sites

So polymorphism is something like inverse operation in math. It does the opposite thing. In general you could create some object as you need them but with polymorphism you would create some group of object that would usually be represented with a single object. Than you would use base class (super class) as your primary class and do specific behavior trough inherited classes. Is this correct ?

##### Share on other sites

So polymorphism is something like inverse operation in math. It does the opposite thing. In general you could create some object as you need them but with polymorphism you would create some group of object that would usually be represented with a single object. Than you would use base class (super class) as your primary class and do specific behavior trough inherited classes. Is this correct ?

Just think of it as a method that allows you to deal with multiple object types as if they were the one and the same. There are many methods that allow something like that, but the built in polymorphism with virtual classes and such is general and flexible, although more specific solutions might be better in a given situation.

##### Share on other sites

So polymorphism is something like inverse operation in math. It does the opposite thing. In general you could create some object as you need them but with polymorphism you would create some group of object that would usually be represented with a single object. Than you would use base class (super class) as your primary class and do specific behavior trough inherited classes. Is this correct ?

Your basic description is roughly correct, but I think the way that you phrased it makes it sound confusing.  In general, polymorphism through inheritance lets you interact with sub-class instances through the interface defined by the base class.  Which methods of the base class are overridden in the sub-classes is not important to the user - they just want to refer to Mammals, and whatever the library creator overrode in each class is just an implementation detail.