Search code examples
c++quantlib

QuantLib date ++ operator overloading


For some reason, QuantLib's Date object ++ overloading operator didn't work as expected but I don't understand why it didn't work. Can someone point out the reason?

There was no error or warning in the following test code.

#include <ql/quantlib.hpp>
#include <ql/time/date.hpp>
#include <iostream>

int main()
{
        QuantLib::Date today = QuantLib::Date::todaysDate();

        std::cout << "today's date is " << today << std::endl;
        std::cout << "tomorrow is " << today++ << std::endl;
        std::cout << "tomorrow is " << today+1 << std::endl;

        return 0;
}

The return is:

today's date is April 27th, 2020
tomorrow is April 27th, 2020
tomorrow is April 29th, 2020

It seems the ++ operator has incremented the day but not display correctly so Date+1 actually increased again to 29. Looks like the difference between ++ and + operators is (in date.hpp):

Date& operator++()
Date  operator++(int )
Date operator+(Date::serial_type days) const;
Date operator+(const Period&) const;

Essentially ++ uses Gregorian object in Boost (in date.cpp)

Date& Date::operator++() {
        dateTime_ +=boost::gregorian::days(1);
        return *this;
    }
Date Date::operator+(Date::serial_type days) const {
        Date retVal(*this);
        retVal+=days;

        return retVal;
    }

Solution

  • When the ++ comes after the variable name, it is called the 'postfix' increment operator. This returns a copy of the variable, then increments the variable itself. This is not necessarily how all overloads of the postfix increment operator have to work, but it is conventional:

    int i = 5;
    int j = i++; //here j is 5
    //i is now 6
    

    To get the behavior you are after, you would use the 'prefix' increment operator, where the ++ comes before the variable name. This increments the variable, then returns a reference to it:

    int i = 5;
    int j = ++i; //here j is 6, as is i
    

    When overloading the operators, overloading the postfix operator requires a dummy argument, where as overloading the prefix operator does not. From your example:

    Date& operator++(); //prefix increment operator
    Date  operator++(int) //postfix increment operator
    

    Therefore, to increment the date variable and return a reference to it, use:

    std::cout << "tomorrow is " << ++today << std::endl; //prefix operator