Thursday 23 February 2012

Polymorphism (Oop concepts)

Polymorphism:


Polymorphism is the key to the power of object oriented programming. It is so important that languages that don’t support polymorphism cannot advertise themselves as OO languages. Languages that support classes but not polymorphism are called object-based languages. Ada is such a languages.
Polymorphism is the concept that support the capability of an object of a class to behave differently in response to a message or action. For instance, ‘human’ is a subclass of ‘Mammal’. Similarly ‘Dog’, ‘Cat’ are also subclasses of ‘Mammal’. Mammals can see through day-light. So if a message ‘see through daylight’ is passed to all Mammals, they all will behave alike. Now if the message ‘see through darkness’ is passed to all the mammals, then human and dogs will not be able to view at night whereas cats will be able to see during night also. Here cats(mammals) can behave differently than other mammals in response to a message or action. This is polymorphism.
Take another example. If you give 5+7, it results in 12, the sum of 5 and 7. And if you give ‘A’ +   ‘BC’, it results into ‘ABC’, the concatenated strings. The same operation symbol ‘+’ is able to distinguish between two operations (summation and concatenation) depending upon the data type it is working on.
Polymorphism is a property by which the same message can be sent to objects of several different classes, and each object can respond in different way depending upon its class.

Implementation polymorphism


C++ implements polymorphism through virtual functions, through overloaded functions and overloaded operators. A virtual function is used to specify the interface is abstract class, but its implementation details are made available by concrete classes, the term overloading means a name having two or more distinct meanings. Thus an overload function refers to a function having more than one distinct meanings. Similarly when two or more  distict meanings are defined for an operator , it is said to be overload operator.
It is compiler job to select the specific action as it applies to each situation. In c++ polymorphism is implemented through overloading and virtual functions.

No comments:

Post a Comment