# How to handle similar actions in derived actors (inheritance)

I have a base class called Attacker that has a update method. The update method moves attacker through an array of waypoints as given below:

- (void) update:(ccTime)dt {
if(state == kMove) {
// code to move to next waypoint
// on reaching the next waypoint, update the next waypoint variable
// if the final waypoint is reached, then stop the movement of attacker
}
}


So, the base class takes care of simple waypoint movement logic. Now I derive a few classes like Rifleman, MachineGunner, Engineer from the Attacker class.

Now I want each of the derived class to do a specific action on reaching the final waypoint. For eg., I want the Rifleman to change to attack stance, the machine gunner to deploy and setup his gun, the engineer to start constructing a defense.

How do I achieve this? My current idea is to check for final waypoint condition in the update method of each of the derived class and do the corresponding action.

- (void) update:(ccTime)dt {
[super update:dt];
if(state == kMove) {
// if the final waypoint is reached, then do class specific action
}
}


Is there any better way of doing this?

• If by "if the final waypoint is reached, then do class specific action" you mean just calling the "endFunction" then yes, polymorphism (en.wikipedia.org/wiki/Polymorphism_(computer_science)) will do the rest. – mikidelux Dec 13 '11 at 10:01
• @mikidelux you should make an answer out of this – bummzack Dec 13 '11 at 10:08
• @mikidelux well if you think your comment is understandable enough, then you can just copy-paste it. But Jari Komppa has already given basically the same answer as of now. – bummzack Dec 13 '11 at 10:11
• I wrote the answer while you were discussing, sorry =) – Jari Komppa Dec 13 '11 at 13:54
• @JariKomppa no probs :) u too answered me right... but i couldnt mark 2 right answers !!! – saiy2k Dec 13 '11 at 15:36

• is calling the endFunction in the update method of base class enough? given the base class have an empty endFunction, which is overridden in the derived classes... am i right? – saiy2k Dec 13 '11 at 10:30