5.2.  Optional Arguments

[ fromfile: functions.xml id: defaultargs ]

Example 5.3. src/functions/date.h

[ . . . . ]
class Date {
public:
    Date(int d = 0, int m = 0, int y = 0);
    void display(bool eoln = true) const;
private:
    int m_Day, m_Month, m_Year;
};
[ . . . . ]

Example 5.4. src/functions/date.cpp

#include <QDate>
#include "date.h"
#include <iostream>



Date::Date(int d , int m , int y ) 
: m_Day(d), m_Month(m), m_Year(y) {
    
    static QDate currentDate = QDate::currentDate(); 1
    
    if (m_Day == 0) m_Day = currentDate.day(); 
    if (m_Month == 0) m_Month = currentDate.month();
    if (m_Year == 0) m_Year = currentDate.year();
}
        

void Date::display(bool eoln) const {
    using namespace std;
    cout << m_Year << "/" << m_Month << '/' << m_Day;
    if (eoln)
        cout << endl;
}

1

We use Qt's QDate class only to get the current date.


Example 5.5. src/functions/date-test.cpp

#include "date.h"
#include <iostream>

int main() {
    using namespace std;
    Date d1;
    Date d2(15);
    Date d3(23, 8);
    Date d4(19, 11, 2003);

    d1.display(false);
    cout << '\t';
    d2.display();
    d3.display(false);
    cout << '\t';
    d4.display();
    return 0;
}

src/functions> qmake
src/functions> make
[ compiler linker messages ] 
src/functions> ./functions
2011/5/14       2011/5/15
2011/8/23       2003/11/19
src/functions>