OOP - Week 6, Lecture 2: Constructors and Destructors in Derived Classes
An Employee Should Start Complete
When a company hires someone, the employee has a name and an id from the first day. In Lecture 1 we created an empty employee and filled it in afterwards:
FullTime f;
f.setName("Omar");
f.setId(1001);
f.setSalary(3000);
Until the last line runs, f is an employee with no name and no id. We solved this problem in Weeks 2 to 5 with constructors: the object is complete from the moment it exists.
FullTime f("Omar", 1001, 3000);
With a derived class, this raises a question: who builds the Employee part of f? The constructor of FullTime cannot do it alone, for two reasons:
- The
nameand theidareprivateinEmployee, soFullTimecannot set them. - Constructors are not inherited:
FullTimedoes not get the constructors ofEmployee.
So the constructor of FullTime has to ask the constructor of Employee to build its part. This lecture shows how, and in which order the constructors and the destructors run.
1. The Order of Construction
A FullTime object has two parts: the Employee part, and the part that belongs to FullTime itself. When the object is created, the base part (the parent) is built first, and then the derived part (the child):
- The constructor of
Employeeruns. - The members of
FullTimeare initialized. - The body of the constructor of
FullTimeruns.
The reason is simple: the derived part may use the base part, so the base part must exist first.
We choose which constructor of Employee runs, in the member initializer list of the derived constructor, by writing the name of the base class and its arguments:
FullTime::FullTime(const string& n, int i, double s) : Employee(n, i), salary(0.0) {
setSalary(s);
}
Employee(n, i) passes the name and the id to the constructor of Employee. Then salary is initialized, and then the body runs.
If you do not write the base class in the initializer list, the compiler calls the default constructor of the base class. If the base class does not have one, the program does not compile:
FullTime::FullTime(const string& n, int i, double s) : salary(0.0) { // no Employee(n, i)
}
error: constructor for 'FullTime' must explicitly initialize the base class 'Employee'
which does not have a default constructor
The exact words depend on your compiler.
In this lecture Employee has no default constructor: its only constructor (apart from the copy constructor) takes a name and an id, so every derived class must call it.
Constructors run from the parent to the child: the base class first, then the derived class.
2. The Order of Destruction
The destructor of the derived class (the child) runs first, and then the destructor of the base class (the parent):
- The body of the destructor of
FullTimeruns. - The members of
FullTimeare destroyed. - The destructor of
Employeeruns.
This is the same rule as for objects in a block: the last thing built is the first thing destroyed. The derived part may use the base part, so it must go before it.
The destructor of FullTime does not call the destructor of Employee. The compiler does it, after the body. Write in each destructor only the cleanup for the members of its own class.
FullTime::~FullTime() {
cout << "~FullTime " << getName() << endl;
}
Destructors run in the opposite order, from the child to the parent: the derived class first, then the base class.
3. The Copy Constructor of a Derived Class
A copy of a FullTime also has an Employee part, and it must be a copy too. The copy constructor of FullTime passes other to the copy constructor of Employee:
FullTime::FullTime(const FullTime& other) : Employee(other), salary(other.salary) {
}
other is a FullTime, but the copy constructor of Employee expects an Employee. This is allowed, because a FullTime is an Employee: the constructor of Employee takes the Employee part of other and copies it.
If you forget
Employee(other), the base part is not copied. The compiler builds it with the default constructor ofEmployee. In this lectureEmployeehas no default constructor, so the program does not compile. If it had one, the program would compile, and the copy would have an empty name and an id of 0 without any warning.
4. A Third Level
A derived class can also be the base of another class. A Manager is a FullTime with a team:
class Manager : public FullTime {
private:
int teamSize;
public:
Manager(const string& n, int i, double s, int t);
};
Manager::Manager(const string& n, int i, double s, int t) : FullTime(n, i, s), teamSize(t) {
}
A class calls only the constructor of its direct base: Manager calls FullTime, and FullTime calls Employee. The Manager does not mention Employee. The order is still from the root:
| ย | Constructors | Destructors |
|---|---|---|
| 1st | Employee | Manager |
| 2nd | FullTime | FullTime |
| 3rd | Manager | Employee |
The destructors are exactly the reverse of the constructors.
5. Putting It Together
This is the Employee, FullTime and PartTime of Lecture 1, now with the constructors that take the data, the copy constructors, the destructors, and the new class Manager. Every constructor and destructor prints a line, so you can see the order. Click Changes since Lecture 1 to see exactly which lines are new. The FullTime f; of Lecture 1 does not compile anymore, because Employee has no default constructor.
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namespace std;
class Employee {
private:
string name;
int id;
public:
Employee(const string& n, int i);
Employee(const Employee& other);
~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(const string& n, int i) : name(n), id(0) {
setId(i);
cout << "Employee " << name << endl;
}
Employee::Employee(const Employee& other) : name(other.name), id(other.id) {
cout << "copy Employee " << name << endl;
}
Employee::~Employee() {
cout << "~Employee " << name << endl;
}
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(const string& n, int i, double s);
FullTime(const FullTime& other);
~FullTime();
void setSalary(double s);
double pay() const;
void print() const;
};
#endif#include <iostream>
#include "FullTime.h"
using namespace std;
FullTime::FullTime(const string& n, int i, double s) : Employee(n, i), salary(0.0) {
setSalary(s);
cout << "FullTime " << getName() << endl;
}
FullTime::FullTime(const FullTime& other) : Employee(other), salary(other.salary) {
cout << "copy FullTime " << getName() << endl;
}
FullTime::~FullTime() {
cout << "~FullTime " << getName() << endl;
}
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(const string& n, int i, int h, double r);
~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(const string& n, int i, int h, double r) : Employee(n, i), hours(0), rate(0.0) {
setHours(h);
setRate(r);
cout << "PartTime " << getName() << endl;
}
PartTime::~PartTime() {
cout << "~PartTime " << getName() << endl;
}
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;
}#ifndef MANAGER_H
#define MANAGER_H
#include "FullTime.h"
class Manager : public FullTime {
private:
int teamSize;
public:
Manager(const string& n, int i, double s, int t);
~Manager();
int getTeamSize() const;
};
#endif#include <iostream>
#include "Manager.h"
using namespace std;
Manager::Manager(const string& n, int i, double s, int t) : FullTime(n, i, s), teamSize(t) {
cout << "Manager " << getName() << endl;
}
Manager::~Manager() {
cout << "~Manager " << getName() << endl;
}
int Manager::getTeamSize() const {
return teamSize;
}#include <iostream>
#include "Manager.h"
#include "PartTime.h"
using namespace std;
int main() {
FullTime f("Omar", 1001, 3000);
FullTime g = f;
g.setName("Nada");
{
Manager m("Sara", 1003, 5000, 4);
} // m is destroyed here
PartTime p("layan", 1002, 20, 12.5);
cout << "end of main" << endl;
return 0;
} // p, g and f are destroyed here#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.