c++classinheritanceclass-hierarchy

Overridden function does not print base class data


I am having an 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?


Solution

  • When you call Employee::businessCard(); it will call const char* name() const { return _name.c_str() ; } of Employee class. But earlier during the construction of the Manager object, you haven't passed name to the base class Employee, so it's not set in Employee class and you got it empty while printing.

    So to make it work, it should be something like

    Manager(const char* name, double salary, set<Employee*>& subordinates) : Employee(name,salary), _subs(subordinates)
    

    and remove _name and _salary member variables from manager as it defeats the purpose of inheritance in this example.