Reputation: 13
I'm attempting to create a date and time class using inheritance.
The parent class, Date, has variables month, day, and year.
The Date derived class, DateTime, has the same variables but with hour, minute, and second added. The DateTime instance, when created, must be passed a Date instance and with optional parameters hour, minute, and second. The Date parameter is a requirement. If the optional parameters are not passed, default values of 0 will be applied.
Is there a more efficient way to implement this? I feel like it is tedious to re-set the parameters by retrieving them using a function in the Date instance for the new DateTime instance.
DateTime::DateTime(Date passDate){
day = passDate.getDay();
month = passDate.getMonth();
year = passDate.getYear();
hour = 0;
minute = 0;
second = 0;
}
DateTime::DateTime(Date passDate, int hourSet){
day = passDate.getDay();
month = passDate.getMonth();
year = passDate.getYear();
hour = hourSet;
minute = 0;
second = 0;
}
DateTime::DateTime(Date passDate, int hourSet, int minuteSet){
day = passDate.getDay();
month = passDate.getMonth();
year = passDate.getYear();
hour = hourSet;
minute = minuteSet;
second = 0;
}
Upvotes: 0
Views: 260
Reputation: 10733
You need to provide copy constructor and assignment operator in both classes with proper validation of input values.
With that you just need to implement getters/setters for both base and derived.
Upvotes: 0
Reputation: 18556
You can call parent class constructor and default parameter values to make your code much more concise:
DateTime::DateTime(const Date& passDate, int hourSet = 0, int minuteSet = 0):
Date(passDate) {
hour = hourSet;
minute = minuteSet;
second = 0;
}
Upvotes: 1
Reputation:
You can use default constructor parameters in order to have a single constructor.
DateTime::DateTime(Date passDate, int hourSet=0, int minuteSet=0, int secondSet=0) {
day = passDate.getDay();
month = passDate.getMonth();
year = passDate.getYear();
hour = hourSet;
minute = minuteSet;
second = secondSet;
}
If any of the hourSet=0
, minuteSet
or secondSet
parameters are omitted, they will automatically be replaced with 0
.
Upvotes: 0