class Manager : public Employee {
public:
new member functions
private:
new data members
};
Syntax 11.1: Derived Class Definition class Derived_class_name : public Base_class_name
|
Manager m;
m.set_salary(68000);
class Manager : public Employee {
public:
Manager(string name, double salary, string dept);
string get_department() const;
private:
string department;
};
TravelClock clock("London", -2);
cout << "The time in " << clock.get_location() << " is "
<< clock.get_hours() << ":" << clock.get_minutes();
class TravelClock : public Clock {
public:
TravelClock(bool mil, string loc, double off);
int get_hours() const;
string get_location() const;
private:
string location;
int time_difference;
};
TravelClock::TravelClock(bool mil, string loc, int diff)
: Clock(mil)
{ location = loc;
time_difference = diff;
while (time_difference < 0)
time_difference = time_difference + 24;
};
Syntax 11.2 : Constructor with Base-Class Initializer Derived_class_name :: Derived_class_name(expressions)
|
int TravelClock::get_hours() const
{ . . .
if (is_military()) /* clock uses military time */
return (h + time_difference) % 24;
. . .
}
int TravelClock::get_hours() const
{ . . .
int h = Clock::get_hours(); /* calls base-class function */
. . .
}
int TravelClock::get_hours() const
{ . . .
int h = get_hours(); /* BAD! calls itself */
. . .
}
vector<Clock> clocks(3);
/* populate clocks */
clocks[0] = Clock(true);
clocks[1] = TravelClock(true, "Rome", -1);
clocks[2] = TravelClock(false, "Tokyo", 5);
for (int i = 0; i < clocks.size(); i++)
cout << clocks[i].get_location() << " time: "
<< clocks[i].get_hours() << ":"
<< setw(2) << setfill('0')
<< clocks[i].get_minutes()
<< setfill(' ') << "\n";
Local time is 21:15
Local time is 21:15
Local time is 9:15
vector<Clock*> clocks(3);
/* populate clocks */
clocks[0] = new Clock(true);
clocks[1] = new TravelClock(true, "Rome", -1);
clocks[2] = new TravelClock(false, "Tokyo", 5);
cout << clocks[i]->get_location() << " time: "
<< clocks[i]->get_hours() << ":"
<< setw(2) << setfill('0')
<< clocks[i]->get_minutes()
<< setfill(' ') << "\n";
Local time is 21:15
Local time is 21:15
Local time is 9:15
class Clock {
public:
Clock(bool use_military);
virtual string get_location() const;
virtual int get_hours() const;
int get_minutes() const;
bool is_military() const;
private:
. . .
};
Syntax 11.3: Virtual Function Definition class Class_name
|