Tuesday 29 November 2011

Inheritance + Virtual Functions = Polymorphism

Continuing my post on INHERITANCE to INHERITANCE AND POLYMORPHISM
Hope u guys hav read dat if not den plz read dat before reding dis....!!
Inheritance is powerful but still u vil think dat v can do without it. Obviously yes .... v can, v have been doing without it coz v still use C language.
But introucing d concept of POLYMORPHISM with inheritance takes d power to the next level.
So remember INHERITANCE + POLYMORPHISM = VERY POWERFUL
We introduce d concept of polymorphism by introducing VIRTUAL FUNCTIONS.
So u should first understand d concept of Virtual functions.
For eg: We create an ENEMY class and we have 20 different types of ENEMIES
class enemy
{
public:
void Attack();
}

So dis becomes our base class for all enemies now if we have like 20 diff. enemies in our game and all of dem have different attacks. So without using Virtual functions
we make 20 classes for diff enemies and all of dem inherit from base class enemy.
den enemy obj = new badEnemy();
enemy obj1 = new BadAssEnemy();
enemy obj2 = new RealBadAssEnemy();

but when we call attack() of all three objects it will call d attack() of base class.....:( so bad na same kind of attack for every enemy makes ur game a dull game,
UNTIL we make dat attack() function "VIRTUAL". Now each enemy class vil have different implementation for their attack() which vil actually make dem different.
like badenemy attack() simply fires a pistol at you while BadAssEnemy's attack() fires a machine gun at you and RealBadAssEnemy's attack() fires rocket launcher at u..!!
Hope ur following d point..it gives us d power to implement d function differently for every class.

No comments:

Post a Comment