Thursday, 15 August 2013

inheritance - C++: Constructors: Parent class parameters and setting values in new instance -



inheritance - C++: Constructors: Parent class parameters and setting values in new instance -

i'm attempting create date , time class using inheritance.

the parent class, date, has variables month, day, , year.

the date derived class, datetime, has same variables hour, minute, , sec added. datetime instance, when created, must passed date instance , optional parameters hour, minute, , second. date parameter requirement. if optional parameters not passed, default values of 0 applied.

is there more efficient way implement this? sense tedious re-set parameters retrieving them using function in date instance new datetime instance.

datetime::datetime(date passdate){ day = passdate.getday(); month = passdate.getmonth(); year = passdate.getyear(); hr = 0; min = 0; sec = 0; } datetime::datetime(date passdate, int hourset){ day = passdate.getday(); month = passdate.getmonth(); year = passdate.getyear(); hr = hourset; min = 0; sec = 0; } datetime::datetime(date passdate, int hourset, int minuteset){ day = passdate.getday(); month = passdate.getmonth(); year = passdate.getyear(); hr = hourset; min = minuteset; sec = 0; }

you can phone call parent class constructor , default parameter values create code much more concise:

datetime::datetime(const date& passdate, int hourset = 0, int minuteset = 0): date(passdate) { hr = hourset; min = minuteset; sec = 0; }

c++ inheritance

No comments:

Post a Comment