OOP - Week 6, Lecture 1: Base and Derived Classes
Two Kinds of Employees, One Id
A company has two kinds of employees. A full-time employee gets a monthly salary. A part-time employee gets paid for the hours worked, at an hourly rate.
The two kinds are different, but they also have a lot in common. Both have a name and an id, both need functions to set them, and both can print them. Everything else is different: the salary for one, and the hours and the rate for the other.
With what we know so far, we write one class for each kind, and the shared part is written twice:
class FullTime {
private:
string name; // shared
int id; // shared
double salary;
public:
void setId(int i); // shared
};
class PartTime {
private:
string name; // shared
int id; // shared
int hours;
double rate;
public:
void setId(int i); // shared
};
The code of setId is copied into both classes. If the rule for a valid id changes, you must remember to change it in both places, and a third kind of employee would need a third copy.
The two kinds of employee are not unrelated: a full-time employee is an employee, and a part-time employee is an employee. What they share belongs in one class, and the rest belongs in the class of each kind. C++ lets one class inherit from another, and this is what this week is about.
1. Base Class and Derived Class
We write the shared part once, in a class Employee. This is the base class. A class that inherits from it is a derived class. After the name of the derived class, write :, the word public and the name of the base class:
class Employee {
private:
string name;
int id;
public:
void setName(const string& n);
string getName() const;
void setId(int i);
int getId() const;
void print() const;
};
class FullTime : public Employee { // a FullTime is an Employee
private:
double salary;
public:
void setSalary(double s);
double pay() const;
};
FullTime now has everything of Employee, and its own salary:
A FullTime object has the name and the id, and setName, setId, getName, getId and print can be called on it, even though FullTime does not mention them. Its own members work as usual:
FullTime f;
f.setName("Omar"); // inherited from Employee
f.setId(1001); // inherited from Employee
f.setSalary(3000); // defined in FullTime
Inheritance is called an βis-aβ relationship: a FullTime is an Employee. It goes in one direction. Every FullTime is an Employee, but an Employee is not necessarily a FullTime, so an Employee object cannot use setSalary: the compiler says no member named 'setSalary' in 'Employee'.
Always write
publicbefore the base class. Without it, the inheritance is private, and the public functions ofEmployeecannot be called on aFullTime:'setId' is a private member of 'Employee'. Section 3 explains the three types of inheritance.
2. What a Derived Class Can Use
An object of a derived class contains the data of the base class: a FullTime object has a name and an id inside it. But a private member belongs to its own class. A derived class cannot use the private members of its base class by name:
void FullTime::print() const {
cout << name; // error: 'name' is a private member of 'Employee'
}
The exact words of an error message depend on your compiler, but the meaning is the same. The derived class uses the public functions of the base class, like any other code. If FullTime needs the name, it calls getName().
So far a member had two choices. With private, nobody outside the class can use it, not even a derived class. With public, everybody can use it. Sometimes we want something in between: a member that the derived classes can use, but the rest of the program cannot. For this, C++ has a third access level, protected:
class Employee {
protected:
int id; // Employee and the classes derived from it can use id
};
class FullTime : public Employee {
public:
void print() const {
cout << id; // allowed: id is protected
}
};
int main() {
FullTime f;
f.id = 5; // error: 'id' is a protected member of 'Employee'
}
In this code, id is protected, so it belongs to the protected row of the table below:
Employeeitself can useid: yes.FullTimeis a derived class, andprint()usesid: yes.mainis the rest of the program, andf.id = 5;fails: no.
Employee trusts FullTime with id because a FullTime is a kind of Employee, but main is outside code, so it is locked out. The table gives the same answer for any member, according to its access level. Find the row of the member, then the column of who is using it:
| A data member declared as | Can the class itself use it? | Can a derived class use it? | Can the rest of the program use it? |
|---|---|---|---|
private | yes | no | no |
protected | yes | yes | no |
public | yes | yes | yes |
Use
protectedonly when a derived class really needs the member. Keeping the dataprivateand giving access through public functions is safer, because the base class stays the only place that decides how its data changes. In this course, the data members stayprivate.
3. The Type of Inheritance
The word before the base class is the type of inheritance: public, protected or private. It decides what access the inherited members have inside the derived class. The table shows the access of each member of Employee in FullTime:
| Member in the base class | : public Employee | : protected Employee | : private Employee |
|---|---|---|---|
public | stays public | becomes protected | becomes private |
protected | stays protected | stays protected | becomes private |
private | not accessible | not accessible | not accessible |
The type of inheritance can only make the access stricter, never looser.
With public inheritance, every member keeps its access, so the outside code can use a FullTime as an Employee. With the other two types, the public functions of Employee are no longer public in FullTime, and the outside code cannot call them on a FullTime. The class itself can still use them:
class FullTime : protected Employee {
public:
void init() {
setId(1); // allowed: setId is protected in FullTime
}
};
FullTime f;
f.setId(1001); // error: 'setId' is a protected member of 'Employee'
With private instead of protected, the same call in main gives 'setId' is a private member of 'Employee'.
Use public inheritance. It is the only type that means βa
FullTimeis anEmployeeβ for the rest of the program, and it is the one used in this course. If you forget the word, the class gets private inheritance, because that is the default of aclass.
4. Redefining a Function
Both FullTime and PartTime should print themselves, and Employee already has a print for the name and the id. A derived class can write its own function with the same name. This is called redefining the function. The new one hides the one of the base class.
void FullTime::print() const {
Employee::print(); // run the print of the base class first
cout << "full time, pay " << pay() << endl;
}
Inside, Employee::print() calls the version of the base class, so the name and the id are not written again in the new function. Without Employee::, the function would call itself and never end.
Which print runs depends on the class of the variable you call it on (f is a FullTime, so FullTimeβs print runs):
f.print(); // the print of FullTime
The hidden function is still reachable from outside, with the class name and :::
f.Employee::print(); // the print of Employee, on the same object
Notice that pay() is a name in both FullTime and PartTime, with a different calculation in each: the salary for one, and the hours times the rate for the other. They do not interfere, because they are in different classes.
5. Putting It Together
The program is split like in Week 3: each class has a header and a .cpp file, and main.cpp uses them. Look at how main calls setName, setId and getName on both kinds of employees, and how each class prints itself. The header of a derived class must include the header of its base class, so FullTime.h and PartTime.h both contain #include "Employee.h", and the header guards make sure Employee is declared only once in main.cpp. The constructors that appear here are only there to give the members a safe starting value. Lecture 2 shows how the constructor of the base class is called.
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namespace std;
class Employee {
private:
string name;
int id;
public:
Employee();
void setName(const string& n);
string getName() const;
void setId(int i);
int getId() const;
void print() const;
};
#endif#include <iostream>
#include "Employee.h"
using namespace std;
Employee::Employee() : name(""), id(0) {
}
void Employee::setName(const string& n) {
name = n;
}
string Employee::getName() const {
return name;
}
void Employee::setId(int i) {
if (i > 0)
id = i;
}
int Employee::getId() const {
return id;
}
void Employee::print() const {
cout << "employee " << name << ", id " << id << endl;
}#ifndef FULLTIME_H
#define FULLTIME_H
#include "Employee.h"
class FullTime : public Employee {
private:
double salary;
public:
FullTime();
void setSalary(double s);
double pay() const;
void print() const;
};
#endif#include <iostream>
#include "FullTime.h"
using namespace std;
FullTime::FullTime() : salary(0.0) {
}
void FullTime::setSalary(double s) {
if (s >= 0.0)
salary = s;
}
double FullTime::pay() const {
return salary;
}
void FullTime::print() const {
Employee::print();
cout << "full time, pay " << pay() << endl;
}#ifndef PARTTIME_H
#define PARTTIME_H
#include "Employee.h"
class PartTime : public Employee {
private:
int hours;
double rate;
public:
PartTime();
void setHours(int h);
void setRate(double r);
double pay() const;
void print() const;
};
#endif#include <iostream>
#include "PartTime.h"
using namespace std;
PartTime::PartTime() : hours(0), rate(0.0) {
}
void PartTime::setHours(int h) {
if (h >= 0)
hours = h;
}
void PartTime::setRate(double r) {
if (r >= 0.0)
rate = r;
}
double PartTime::pay() const {
return hours * rate;
}
void PartTime::print() const {
Employee::print();
cout << "part time, " << hours << " hours at " << rate << ", pay " << pay() << endl;
}#include <iostream>
#include "FullTime.h"
#include "PartTime.h"
using namespace std;
int main() {
FullTime f;
f.setName("Omar");
f.setId(1001);
f.setSalary(3000);
PartTime p;
p.setName("layan");
p.setId(1002);
p.setHours(20);
p.setRate(12.5);
f.print();
p.print();
p.Employee::print();
cout << "name of p: " << p.getName() << endl;
cout << "total pay " << f.pay() + p.pay() << endl;
return 0;
}Click each line of output to see what caused it.