Polymorphism in C++

05 min read

 

  • Polymorphism means – 'one name, multiple forms'. 
  • The overloaded member functions are 'selected' for invoking by matching arguments, both type and number. Since this information is known to the compiler at compile time, the compiler is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or static binding or static linking. Also known as compile-time polymorphism, early binding simply means that an object is bound to its function call at compile time. Achieved using function overloading and operator overloading. 
  • The appropriate member function can also be selected at runtime. This is known as runtime polymorphism. Also called late binding or dynamic binding which is achieved using virtual functions.

 

 

Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.

  • Function Overloading: When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by the change in the number of arguments or/and change in the type of arguments.
  • Operator Overloading: C++ also provides option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two strings. We know that this is the addition operator whose task is to add to operands. So a single operator ‘+’ when placed between integer operands, adds them and when placed between string operands, concatenates them.

Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.

  • Function overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error