Given a Teacher class that derives from a Faculty class, how would I handle the name of a Teacher object, which is defined as a private member in Faculty but not in Teacher, for copy control?
// example code for the two classes
class Faculty{
public:
/* constructor
copy constructor
destructor
assignment operator
*/
string get_name() const{
return name;
private:
string name;
};
class Teacher : public Faculty{};
Assuming that Faculty class has a functioning copy control
// Copy constructor
Teacher(const Teacher& rhs) : Faculty(rhs){
name = rhs.name;
}
This line doesn't compile because it tries to access a private member of Faculty. Is this line needed or is the name of the copy already set to rhs.name by the initialization list, Faculty(rhs)? Would name be accessible if I directly define a string name in the private field of Teacher?
// Assignment operator
Teacher& operator=(const Teacher& rhs){
Faculty::operator=(rhs);
if(this != &rhs){
name = rhs.name; // same issue
}
return *this;
}
Same issue as copy control, is this needed or is the name already changed to rhs.name by the Faculty class's assignment operator?
CodePudding user response:
Is this line needed or is the name of the copy already set to rhs.name by the initialization list, Faculty(rhs)?
No the line is not needed (assuming a default or properly implemented Faculty
copy constructor). The Faculty
constructor will assign or initialise name
for you properly.
Would name be accessible if I directly define a string name in the private field of Teacher?
Yes, kind of. But it will be an entirely separate instance of name
. You don't want to do this. You only want name
defined once.