I am trying to use nested classes instead of multiple inheritance. I am following the recommendations from the book but I keep getting an error in the constructor. Basically, Person is the grandfather, Student and Employee are the Parent and Teaching Assistant is the child. TeachingAssistant will have a nested class that will have reference to its outer class, but when I use the code from the book I get two errors
I get the error
Error 1 *"No matching constructor for Initialization of TeachingAssistant::EmployeePart"
and this error
Error 2 "Out of line definition of 'EmployeePart' does not match any declaration in 'TeachingAssistant::EmployeePart'"
Here is the code:
class TeachingAssistant : public Student
{
public:
TeachingAssistant();
private:
class EmployeePart;
EmployeePart* employee_ptr;
};
class TeachingAssistant::EmployeePart : public Employee
{
public:
EmployeePart(TeachingAssistant&);
private:
TeachingAssistant* ta_part; // Allows access back to outer class
};
Error 1 is here in this constructor
TeachingAssistant::TeachingAssistant()
{
employee_ptr = new EmployeePart(this); // Pass pointer to implicit parameter
}
Error 2 is here
TeachingAssistant::EmployeePart::EmployeePart(TeachingAssistant* taval)
: ta_part(taval) {}
Why do these errors pop up if I am providing the constructors?
Your basic problem is that you have called the EmployeePart constructor wrongly, and defined it wrongly. However, while we are fixing that, we will also address the fact that you should prefer to not use new
, and not to use raw pointers that own memory, and not to use pointers when you don't need nullability or reseatability.
class TeachingAssistant : public Student
{
public:
TeachingAssistant();
TeachingAssistant(const TeachingAssistant&rhs) = delete; // Delete copy constructor.
TeachingAssistant& operator=(const TeachingAssistant&rhs) = delete; // And assignment.
private:
class EmployeePart;
std::unique_ptr<EmployeePart> employee_ptr; // First change here.
};
class TeachingAssistant::EmployeePart : public Employee
{
public:
EmployeePart(TeachingAssistant&);
private:
// Second change here. Store reference, not pointer.
TeachingAssistant& ta_part; // Allows access back to outer class
};
Create the employee_ptr
in the initialization list, and pass *this
, not this
.
TeachingAssistant::TeachingAssistant()
: employee_ptr(std::make_unique<EmployeePart>(*this)) // Pass reference to constructor
{
}
Fourth change is on next line:
TeachingAssistant::EmployeePart::EmployeePart(TeachingAssistant& taval)
: ta_part(taval) {}