mercredi 15 janvier 2020

C++11 Question regarding class-hierarchy and inheritance

Dear stackoverflow users,

I am having a little issue with the class inheritance in my code. Here is what I am doing: I have two classes, one called Employee and the second called Manager. Employee is the base class, it has a function that prints Business card, containing the name of the company and the function name(), that prints the name of the employee. Class Manager is a derived class and inherits (public: Employee). When I try to print the same business card for the manager, it does not display the name, only the company name. What could be the problem? Below is the little snippet of, first, the Employee class:

class Employee {

public:
  // Constructor
  Employee(const char* name, double salary) : _name(name), _salary(salary) {}
  Employee() : _name(" "), _salary(0) {} // default constructor
  // Accessors
  const char* name() const { return _name.c_str() ; }
  double salary() const { return _salary ; }
  // Modifyers (if needed)
  double set_salary( double salary) { 
      _salary = salary;
      return _salary;
  }

  // Print functions
  void businessCard(ostream& os = cout) const {
    os << "   +------------------+  " << endl
       << "   | ACME Corporation |  " << endl 
       << "   +------------------+  " << endl
       << "   " << name() << endl ;
  }

private:

  string _name ;
  double _salary ;

} ;



and, secondly, the Manager class:

class Manager : public Employee {

public:

// Constructors
Manager(const char* name, double salary, set<Employee*>& subordinates) : 
    _name(name), _salary(salary), _subs(subordinates) {}

...

// Accessors
const char* name() const { 
    string name;
    name += _name;
    name += " (Manager)"; 
    return name.c_str() ; 
}

void businessCard(ostream& os = cout) const {
    Employee::businessCard();
}

private:
    string _name ;
    double _salary ;
} ;

The problem, as I think, is in the name() function, because if I write it explicitly, it appears on the card, though it is not inherited. Could anyone help?

Aucun commentaire:

Enregistrer un commentaire