Why use polymorphism for grading activities?

  • Thread starter yungman
  • Start date
In summary,The PassFailActivity object has a minimum passing score of 70 and a points each value of 100.
  • #36
@yungman, inasmuch as there was some discussion in this thread about overloading, I though I would throw in an example that is somewhat in the same vein, in which multiple versions of two functions are created at compile time.

This is really about template functions, a topic you probably haven't seen yet.
C++:
// TemplateFn.cpp - Example of a templatized function
#include <ccomplex>
#include <iostream>
using std::complex;
using std::cout;
using std::endl;

template <class T>                // Template function for sum
T sum(T a, T b) { return a + b; }

template <class T>                  // Template function for product
T prod(T a, T b) { return a * b; }int main()
{
    // Create three instances of each template function
    int a = 3, b = 5;
    // Call sum() and prod() with int arguments
    int intRet1 = sum<int>(a, b);
    int intRet2 = prod<int>(a, b);
    cout << "Integer sum: " << intRet1 << " product: " << intRet2 << endl;

    double c = 2.5, d = 3.8;    
    // Call sum() and prod() with double arguments
    double dblRet1 = sum<double>(c, d);
    double dblRet2 = prod<double>(c, d);
    cout << "Double sum: " << dblRet1 << " product: " << dblRet2 << endl;

    complex<double> e = { 2.5, 3.0 }, f = { 6.0, -2.0 };
    // Call sum() and prod() with complex arguments
    complex<double> cmplxRet1 = sum<complex<double>>(e, f);
    complex<double> cmplxRet2 = prod<complex<double>>(e, f);
    cout << "Complex sum: " << cmplxRet1 << " product: " << cmplxRet2 << endl;    
}

Output:
Code:
Integer sum: 8 product: 15
Double sum: 6.3 product: 9.5
Complex sum: (8.5,1) product: (21,13)
In the last line, the sum is 8.5 + 1i, and the product is 21 + 13i, the usual notation for complex numbers that mathematicians use.
 
  • Informative
  • Like
Likes sysprog and FactChecker
Technology news on Phys.org
  • #37
As I think I mentioned in another thread, another important use for operator overloading is when you've defined some object and you want to be able to use it with a standard container such as inserting it into a std::set or using it as a key for std::map. In order to do that, operator< needs to be defined for your object. (If you use the unordered versions of these containers, then you don't need operator<, but you need to write a hash function, which is at least as much work.)
 
  • Like
Likes sysprog

Similar threads

Back
Top