CS333 - Problem Solving and Object Oriented Programming in
C++
[ Home | Schedule
| Personal
Progress | Search | Glossary | Help
]
Simple Explanation | Intro to Inheritance |
Advanced Explanation |
DESCRIPTION |
|
EXAMPLES Click here for more examples |
//This examples adds an alarm feature to the "Time" class in figure 7.1 // Here is the header file #include "time5.h" // definition of base class class AlarmClock : public Time { // AlarmClock inherits basic clock features from Time base class public: // constructors // next constructor just sets time not alarm // we will pass these parameters through to base class AlarmClock(int hour = 0, int minute = 0, int second = 0); // next constructor just sets time and alarm // first three parameters passed to base class // and last three used here AlarmClock(int hour, int minute, int second, int alarmHour, int alarmMinute, bool alarmSet); // sets alarm time and switches alarm on void setAlarmTime(int hour, int minute); // return the hour that alarm is set to int getAlarmHour( ) const; // don't forget to distinguish "const" functions // return the minute the alarm is set to int getAlarmMinute( ) const; // state of alarm is set to true for on or false for off void setAlarm(bool state); bool getAlarm( ) const; private: // already have three data members from base class // add new ones to handle new features int alarmHour; int alarmMinute; bool alarmState; // if true, alarm set, else not set }; // just show unusual code in implementation - click to get full source AlarmClock::AlarmClock(int hour, int minute, int second) : Time(hour, minute, second) // construct base class object 1 { alarmHour = 0; alarmMinute = 0; alarmState = false; // alarm is not set } // next constructor just sets time and alarm AlarmClock::AlarmClock(int hour, int minute, int second, int aHour, int aMinute, bool aState) : Time(hour, minute, second), alarmHour(aHour), alarmMinute(aMinute), alarmState(aState) { } // all work done in constructor initializer 2
|
SYNTAX | class derived-class-name : public base-class-name |
TIPS |
|