Saturday, December 16, 2017

OO C++ Compound Interest

Before creating something as complex as a compound interest calculator, let's create a simple example showing how to develop and use a C++ class.
#include <iostream>

using namespace std;

class OODate
{
  int yr, mo, day;

  public:
    OODate(int yr, int mo, int day); // declare the constructor
    string toString()                // define the toString method
    {
      return to_string(mo) + "/" 
           + to_string(day) + "/" 
           + to_string(yr);
    }
};

OODate::OODate(int y, int m, int d) // define the constructor
{
  yr = y; mo = m; day = d;
}

int main() 
{
  OODate dt(2017, 12, 16);       // use the constructor
  cout << dt.toString() << endl; // call the method we coded
}

A Larger Example
#include <iostream>
#include <cmath>
using namespace std;

class IntRateCalculator {
public:
    IntRateCalculator(double rate);
    IntRateCalculator(const IntRateCalculator &v);
    IntRateCalculator &operator =(const IntRateCalculator &v);
    ~IntRateCalculator();
    double singlePeriod(double value);
    double multiplePeriod(double value, int numPeriods);
    double continuousCompounding(double value, int numPeriods);
private:
    double m_rate;
};

// constructor
IntRateCalculator::IntRateCalculator(double rate)
: m_rate(rate){}

// destructor
IntRateCalculator::~IntRateCalculator(){}

inline double IntRateCalculator::singlePeriod(double value)
{
    double f = value * ( 1 + this->m_rate );
    return f; 
}

IntRateCalculator::IntRateCalculator(const IntRateCalculator &v)
: m_rate(v.m_rate){}

// overload = operator
IntRateCalculator &IntRateCalculator::operator =(const IntRateCalculator &v)
{
    if (&v != this)
    {
        this->m_rate = v.m_rate;
    }
    return *this;
}

double IntRateCalculator::multiplePeriod(double value, int numPeriods)
{
    double f = value * pow(1 + this->m_rate, numPeriods);
    return f; 
}

double IntRateCalculator::continuousCompounding(double value, int numPeriods)
{
    double f = value * exp(m_rate * numPeriods);
    return f; 
}

int main() {
  IntRateCalculator i(0.070);
  cout << i.singlePeriod(100000) << endl;
  cout << i.multiplePeriod(100000, 6) << endl;

  i = 0.01;  // use overloaded = operator
  cout << i.multiplePeriod(100000, 6) << endl;

  cout << i.continuousCompounding(100000, 6) << endl;

  return 0;
}

Compile, Link and Run
$ g++ -std=c++14 -c -o IntRateCalculator.o IntRateCalculator.cpp
$ g++ -o IntRateCalculator IntRateCalculator.o
$ ./IntRateCalculator
107000
150073
106152
106184