Tuesday, 29 November 2011

C++ Inheritance Explained


inheritance is a feature which allows us to easily create new class based on already created classes. By deriving from dem and adding more functionality.
suppose we just finished creating our class for ENEMY which takes care of enemies animations, health and ai. we use dese enemies in d whole level and wen d ending of d level comes v hav to create a boss for d level. so instead of creating a new class boss we inherit d ENEMY class and add some more functionality because even the boss vil hv animations ,health and ai. So we dnt hv to write d code again for dese thngs.

Inheritance is a very powerful tool but u shud use it wisely....

Rules wether to inherit or not.

Rule 1. should be "Is a" relationship and not "Has a" relationship
derived class should follow IS A model...like BOSS is an ENEMY so it can inherit enemy class.
"has a" relationship should be followed when conatinment is to be applied.
For eg: we have a class for weapons. So should weapon class inherit enemy class?
NO..coz a weapon is not an enemy we can also hav a weapon.
But an ENEMY has a WEAPON so it follows HAS A relationship.
hence enemy class vil hav an object of WEAPON class inside it as its member.

Rule 2. There should be beahvioral change and not only data change
For eg: our boss class satisfies d 1st rule but suppose our boss is dumb and acts and looks xactly d same with only difference being its health.
suppose normal enemy int health = 100;
Boss health = 200;
so dere is only chnge in data bt nt in d beahvior of boss so it fails d inheritance eligibility.
But suppose our BOSS is very powerful and can also attack us from air where as normal enemy can only attack from land. Then there is also behavioral change.Then we should inherit d enemy class.

while designing architectures inheritance shud be used carefully it can either simplify ur design or make ur nights sleepless.
These are d 2 thumb rules that u shud always consider while deciding wether to inherit or not.

No comments:

Post a Comment