Polymorphism problem statement
In the previous post, we saw a possible way to fire a series of artillery guns in quick succession:
void synchronized_fire() {
howitzer_v1_fire(GUN_ID1);
dhanush_fire(GUN_ID2);
bofors_v2_fire(GUN_ID3);
howitzer_v2_fire(GUN_ID4);
dhanush_fire(GUN_ID5);
}
And we asked ourselves, what's wrong in writing the function this way?
Well, to start with, adding a new gun will need us to change this function and re-compile.
Next, suppose we need a new routine of firing - like triggering alternate guns to save ammunition. Then we need two functions to fire odd and even guns:
void synchronized_fire_odd() {
howitzer_v1_fire(GUN_ID1);
bofors_v2_fire(GUN_ID3);
dhanush_fire(GUN_ID5);
}
void synchronized_fire_even() {
dhanush_fire(GUN_ID2);
howitzer_v2_fire(GUN_ID4);
}
Gradually, such functions proliferate. After this, adding a new type of gun (or replacing an obsolete piece) will trigger change in all those functions.
Is there a better way to do it in C? Do you think we can use function pointers? Read on...
Yes. We could use a structure for each artillery gun with a function pointer and use the pointer with the companies fire function
ReplyDeleteIndeed Pushkaraj, you've hit the point. Your idea leads to more capabilities!
DeleteThis got me thinking... what if each gun needed an encrypted code to fire (to ensure only authorized triggers)? We could include that code in the struct too.
With this we encapsulate the data and the functionality together!
Thanks for the response :)