<<< Encapsulation + inheritance + polymorphism     Index     Inheritance Goals >>>

7. Run-time polymorphism vs. parametric polymorphism

  • C++ also supports parametric polymorphism, also known as compile-time polymorphism:

    • Unlimited number of polymorphic behaviors

    • Programmer creates a template

    • Compiler determines concrete implementation at compile-time.

  • For example,

    
    template< typename ValueT >
    void swap( ValueT& one, ValueT& another )
    {
        ValueT temp = one;
        one = another;
        another = temp;
    }
    
    #include <cassert>
    
    int main()
    {
        double dbl1 = 0.1;
        double dbl2 = 0.2;
        swap( dbl1, dbl2 ); // swap two doubles
        assert( dbl1 == 0.2 && dbl2 == 0.1 );
    
        int int1 = 1;
        int int2 = 2;
        swap( int1, int2 ); // swap two integers
        assert( int1 == 2 && int2 == 1 );
    
        return 0;
    }
    
    
<<< Encapsulation + inheritance + polymorphism     Index     Inheritance Goals >>>