Polymorphism in c++


  • Polymorphism (from Greek, meaning “many forms”) is the quality that allows one interface to access a general class of actions.
  • A simple example of polymorphism is found in the steering wheel of an automobile. The steering wheel (the interface) is the same no matter what type of actual steering mechanism is used.
  • That is, the steering wheel works the same whether your car has manual steering, power steering, or rack-and-pinion steering.
  • Polymorphism helps reduce complexity by allowing the same interface to specify a general class of action.

Example

    #include <iostream.h>
    using namespace std;
    class Add {
    public:
      int sum(int num1, int num2){
         return num1+num2;
      }
      int sum(int num1, int num2, int num3){
         return num1+num2+num3;
      }
    };
    int main() {
      Add obj;
      //This will call the first function
      cout<<"Output: "<<obj.sum(10, 20)<<endl;
      //This will call the second function
      cout<<"Output: "<<obj.sum(11, 22, 33);
      return 0;
    }
    

Output

    Output: 30
    Output: 66