0
Hello guys am not getting my head around polymorphism in c++ what can be done
c++ polymorphism
3 Respostas
+ 9
hello..
it is about making a function that can be used in different ways based on the object calling it..
+ 3
Lol
here is an example
https://code.sololearn.com/cKi0cyBr24H2/?ref=app
- 1
To me polymorphism is about how to group similar objects/class variables together.
Let’s say you wanted to model a zoo with 10 animals.
How do you keep track of all the animals and how they speak or move?
You can have objects for each animal e.g.:
Tiger t1=new Tiger();
Tiger t2=new Tiger();
...
Monkey m1=new Monkey();
Or:
Tiger [] t = new Tiger [2];
...
Monkey [] m = new Monkey [1];
However you would need to call speak via:
t1.speak(); or
t[0].speak(); and so on...
Polymorphism allows you group them.
If you had ten animals total but only six 3 types (e.g. Tiger, Monkey, and Horse). You can do something like:
var Animals [][] zoo = new Animal [3][];
zoo [0] = new Tiger [5];
zoo [1] = new Monkey[2];
zoo [2] = new Horse [3];
Hence they are all together and you can make each animal speak without separate variables like so:
for (i =0; i<zoo.length(); i ++){
if (zoo[i].length()>0){
Print (we have zoo[i].length() zoo[i].[0].typeOfAnimal)
Print (Hear us speak)
Print (zoo[i].[0].speak()
}
}
Sorry if syntax is not correct but logic should be right.
Or if you play shooter games like doom you would put all the weapons for the user in an array of weapons (e.g. handgun, machine gun, rocket...)