Problem Solution: Inheritance And Whole/Part Relationships
class Employee : public Person
{
private:
Record myRecord;
Project* myProject = nullptr;
int id;
public:
Employee(string name, double s, int i)
: Person(name), myRecord(s), id(i) {}
~Employee() { if (myProject != nullptr) delete myProject; }
void set_project(char a_code)
{
if (myProject != nullptr)
delete myProject;
myProject = new Project(a_code);
}
void display()
{
Person::display();
myRecord.display();
if (myProject != nullptr)
myProject->display();
cout << id << endl;
}
};
- Use the superclass's name to call the superclass constructor. The call to the superclass constructor must be the first element of the initializer list. The order of the other elements is not significant. In the "old days," it was not possible to initialize member variables when they were declared, so they were initialized in the initializer list:
myProject(nullptr)
- The if-statement prevents memory leaks and illustrates why it is important to class-scope pointers.
- The calling order is not syntactically significant.