Programming/Non programming

Friday, April 16, 2010

C++:Polymorphism

C++ Concept: Polymorphism (also includes UPCASTING, VTABLE, "late-binding" or "dynamic-binding", Pure Virtual Function, )


"Polymorphism" is one of the strongest OOP(Object Oriented Programming) concept in C++. It is the ability to redefine the methods for derived classes. It can be said like call different function with one type of function call. Using "Virtual" function, this polymorphic concept is being done, so the base class function must be declared as "virtual".

Example I

1. Consider there is a base class as "Shape".
2. Consider there may be derived classes such as Circles, Rectangles and Triangles.
3. There could be a method called "area(...)" as "virtual" method. It acts as "Polymorphism". Because it could be called in all the three derived classes, but it will give you the correct results for every classes as it needed.

Example II

1. Consider a base class called "base"


class base {
        
      public:
         void func()
         {
              cout<<"This is from base class";
         }
};


2.  Derived two classes from the base class like below:


class derived1 : public base
{
      public:
        void func ()
        {
              cout<<"This is from derived class1";
        }
};


class derived2 : public base
{
       public:
          void func()
          {
               cout<<"This is from derived class2";
          }


};


Note down all the classes has a function called "func()" as same:


You:
Does it mean polymorphism?


Me:
NO...........then Why and How?


Lets say i'm outputting the result as below which is a normal procedure:


void main()
{
        derived1 der1;
        derived2 der2;
        
        // The below concept till the END is called "UPCASTING" in c++
        base *b;
        b = &der1;
        b->func();
     
        b = &der2;
        b->func();
        // END
}


[ "UPCASTING" :-  Pointer of a base class to accept addresses of derived classes ]

The output will be:

"This is from base class"
"This is from base class"


You:
Why? What happened? You said "Polymorphism" mean different functions but one type of call etc. in this post initially? Why doesn't it happen here?


Me:
Compiler looks at the above code and calls the function which has type of pointer (base class) .
The earlier one doesn't handle "Virtual" function in the base class, so it is nothing but calling non-virtual functions normally. That's the reason, base class output will be called twice as seen in the above output.
I also said after sometimes, "Virtual" function is the one handles polymorphic logic. So check the below definitions.

3. Add function as "virtual" function in "base" class, which is very important here.


class base {
        
      public:
         virtual void func()
         {
              cout<<"This is from base class";
         }
};









Now, the output will be:

"This is from derived class1"
"This is from derived class2"



Now, we got the output properly. Why and How? "Virtual" function makes the Polymorphism now.

Now, the compiler looks at contents of the pointer. Hence it's addresses pointing to derived classes, it calls derived call functions properly.


But still compiler doesn't know which function to call at compile-time. It decides which function to call at Run-time with the help of VTABLE (described about it below). Compiler uses this table to find what is to be pointed and call the respective functions.
This concept is, compiler decides which function is to be called at Run-time, called "late-binding" or "dynamic-binding".



Pure Virtual Function:


You can realize from the above code is that, "base" class function is never being called. So, keep this body blank anyway like below. It is called "Pure Virtual Function".








class base {
        
      public:
         virtual void func()=0;  // Pure Virtual Function
};


One more point here is, if the base class has "Pure Virtual Function" (like the example just above), then object of that class cann't be created. The one can use only "derived1" and "derived2" and access virtual function (As per our examples mentioned above in void main() function).

When do need "Pure Virtual Function":

When a virtual function would not be needed to create base class object, then use base class method as Pure Virtual function, where we can't created an object on that.


How does the Virtual function work using VTABLE:


Every class has VTABLE where it stores the functions that it can access. Each class VPTR that can access VTABLE.


First check-out our virtual function code below






class base {
        
      public:
         virtual void func()
         {
              cout<<"This is from base class";
        }
       virtual void output()
       {
             cout<<"Final Output";
      }

};




class derived1 : public base
{
      public:
        void func ()
        {
              cout<<"This is from derived class1";
        }
};

class derived2 : public base
{
       public:
          void func()
          {
               cout<<"This is from derived class2";
          }

};




void main()
{
        derived1 der1;
        derived2 der2;
      
        base *b;
        b = &der1;
        b->func();
     
        b = &der2;
        b->func();
        b->output(); 

        derived1 der2;
        b = &der2;
        b->func();
        b->output();
}



VTABLE for the above code is below:


Base Pointers            Objects                                    VTABLES


b   ---------------     base(VPTR)                           --   &base:func()
                                                                                  &base:output()


b   ---------------     derived1 der1, der2(VPTR) --   &derived1:func()


b   ---------------    derived2 der2(VPTR)           --    &derived2:func()         


First VPTR is initialized by the compiler automatically from the constructor called in base class. The next VPTR are created for when virtual function to be called.
If the function is not present in the VTABLE, then it calls the base class method of the same function. Here is output() method called like that.




I hope this simple example explanation and code sample described above should help someone who are newbie to C++ language programming.







Cheers!

M.P.Prabakar
Senior Systems Analyst.


Have fun and be addictive by playing "TossRing" marvelous iPhone game. Link is below..