I've split the code into 2 pieces. However I've failed to call the SetDate function. How do I call a method that's a part of a class but put outside of it? In the .cpp how do I call SetDate fx? I've tried a few different ways.
#ifndef DATE_H
#define DATE_H
class Date
{
private:
int m_year;
int m_month;
int m_day;
public:
Date(int year, int month, int day);
void SetDate(int year, int month, int day);
int getYear() { return m_year; }
int getMonth() { return m_month; }
int getDay() { return m_day; }
};
#endif
#include <iostream>
#include "date.h"
int main ()
{
Date date1;
std::cout << "The first date is "
<< date1.getDay() << "/" << date1.getMonth() << "/" << date1.getYear() << ".\n";
Date date2(2016, 8, 1);
std::cout << "The second date is "
<< date2.getDay() << "/" << date2.getMonth() << "/" << date2.getYear() << ".\n";
}
The first date is 1/1/1970.
The second date is 1/8/2016.
#include <iostream>
#include "date.h"
int main ()
{
Date date1;
std::cout << "The first date is "
<< date1.getDay() << "/" << date1.getMonth() << "/" << date1.getYear() << ".\n";
Date date2(2016, 8, 1);
std::cout << "The second date is "
<< date2.getDay() << "/" << date2.getMonth() << "/" << date2.getYear() << ".\n";
std::cout << "\nAgain, the second date is " << date2 << ".\n";
}
The first date is 1/1/1970.
The second date is 1/8/2016.
Again, the second date is 1/8/2016.
I think you should also become familiar with the constructor having a member initialization list:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Date constructor
Date::Date(const USHORT yearArg, const USHORT monthArg, const USHORT dayArg)
: // colon introduces initialiser list
year(yearArg), // direct initialisation not assignment
month(monthArg), //same order as class delcaration
day(dayArg) //make sure to initialise all of them
{
//SetDate(year, month, day);
// do validation here, throw if there is a problem
// invariants - call private functions to keep this tidy
// valid range for year
// valid range for month
// valid range for day
// Leap Year validation for month and day
// object is not deemed to have been created until the end of the constructor is reached
}
You can still have the SetDate function for when the date is changed after the object is created.
Having the SetDate function and calling it from the ctr seems like a good idea, but it is a little inefficient. Before the opening brace of the ctr, the compiler assigns default values for each member variable; if one then gives them values by assignment - that is where the inefficiency lies - it is happening twice and there are unnamed temporaries being created. The member initializer list avoids this.
Recently have been introduced to c++11 uniform initialization list for constructors. The problem at hand here was the constructor wasn't called. Thanks for the perspective on the greater issues and to everyone who contributed.