S
S
Symbi0t2017-08-11 22:51:44
OOP
Symbi0t, 2017-08-11 22:51:44

How to define new methods in derived classes?

Greetings.
There is the following task. There is a list of two types of employees: employee and manager.
Defined the appropriate classes for them:

class Person
{
public:
  virtual void show() = 0;
};

class Employee: public Person
{
public:
  void show()
  {
    std::cout << "Employee" << std::endl;
  }
};

class Manager: public Person
{
public:
  void show()
  {
    std::cout << "Manager" << std::endl;
  }
};

Also, I created a factory:
class PersonFactory
{
public:
  static Person* create(const std::string &type)
  {
    if (type == "Employee")
      return new Employee();
    if (type == "Manager")
      return new Manager();

    return NULL;
  }
};

Now we can create objects of the required dynamic type: The manager has a list of subordinate employees. Accordingly, the class must contain the getListEmployee() method. But if we add it to the Manager class, we will have to add it to the parent Person class as well.
Person* emp = PersonFactory::create("Manager");
emp->getListEmployee(); // Будет ошибка, т.к. метод не определен в родительском классе

But according to the general concept, an ordinary employee cannot have subordinates. So the getListEmployee() method is not needed by the parent Person class.
How to be in that case? How to define new methods in parent classes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2017-08-12
@jcmvbkbc

But according to the general concept, an ordinary employee cannot have subordinates. So the getListEmployee() method is not needed by the parent Person class.

Whether a class needs a method or not depends on its responsibility. If you are going to use Person to work with employees of any type (by the way, a bad class name does not reflect the essence), and some employees can in principle have subordinates, then some method for this should be present in Person. The usability of this interface will depend on the implementation.
So, for example, you can add a getListEmployee() method that returns a list of subordinates (by the way, again, the name of the method is bad, it does not reflect the essence), and the implementation of this method in the Employee class can return an empty list.
Or you can add a getSubordinateEnumerator() method that returns the subordinate enumeration interface, and return NULL from this method in the Employee class.
If you are not going to use the single Person interface, but, for example, will try to cast Person* to Employee* or Manager* type using dynamic_cast, then the method in Person is not needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question