Header

Thursday 5 September 2013

IGNOU BCA 3rd sem Solved Assignment - What is polymorphism? What are different forms of polymorphism? Explain implementation of polymorphism with the help of a C++ program

What is polymorphism? What are different forms of polymorphism? Explain implementation of polymorphism with the help of a C++ program
Ans
Polymorphism is a generic term that means 'many shapes'. In C++ the simplest form of Polymorphism is overloading of functions, for instance several functions called SortArray( arraytype ) where sortarray might be an array of ints, or doubles.
We're only interested here though in the OOP form of polymorphism. This is done by making a function (e.g. Draw() ) virtual in the base class Point and then overriding it in the derived class Circle.

Although the function Draw() is virtual in the derived class Circle, this isn't actually needed- it's a reminder to me that this it is virtual. If the function in a derived class matches a virtual function in the base class on name and parameter types, it is automatically virtual.

Polymorphism is the ability of an object or reference to take many different forms at different instances. These are of two types one is the "compile time polymorphism" and other one is the "run-time polymorphism".
Compile time polymorphism:
In this method object is bound to the function call at the compile time itself.
Run time polymorphism:
In this method object is bound to the function call only at the run time.
Example:
#include <iostream.h>
class Value
  {
    protected:
    int val;
    public:
    void set_values (int a)
      { val=a;}
  };
class Cube: public Value
  {
  public:
  int cube()
    { return (val*val*val); }
  };
int main () {
  Cube cb;
  Value * ptr = &cb;
  ptr->set_values (10);
  cout << "The cube of 10 is::" << cb.cube() << endl;
  return 0;
}
Result:


    The cube of 10 is:: 1000
In the above OOPs example "Cube" is a derived class of "Value". To implement polymorphism a pointer "ptr" is used to reference to the members of the class "Cube". This is an example for "Compile time polymorphism."


For implementation of polymorphism
Virtual Function:
virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to asdynamic linkage, or late binding

No comments:

Post a Comment