0

I am trying to create a extensive database for a company. I have made different classes for every level of employee. But i don't understand how do i push different type objects in a single map.

As far as i have tried it just gets pushed, shows no compilation error as for now atleast.

class EmployeeClass
{}

class CEOClass: public EmployeeClass
{}

class ManagerClass:public EmployeeClass
{}

class EngineerClass: public EmployeeClass
{}

int main()
{
    EngineerClass engineerClassObject;
    std::map<std::string employeeName, EmployeeClass> employeeMap;

    employeeMap.insert({employeeName, enginerrClassObject});
}

I want to understand if i can do this. If not what is the best way of doing this without adding extra maps. If yes how is possible and how does it work?

3 Answers3

0

Virtual Polymorphism kicks in when you have reference/pointer to the base object.

EmployeeClass *engineerClassObject = new EngineerClass();
std::map<std::string, EmployeeClass*> employeeMap;

employeeMap.insert({employeeName, engineerClassObject});

and then

employeeMap["some_emp_name"]->some_virtual_function();
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
  • 2
    I would use a smart pointer instead for memory management, e.g. std::shared_ptr pEngineer = std::make_shared(); – jignatius Jun 24 '19 at 10:04
0

You can use pointers or references.

Here an exsample with pointers and std::pair.

int main()
{
    EngineerClass engineerClassObject;
    std:string employeeName = "Peter";
    std::map<std::string employeeName, EmployeeClass*> employeeMap;

    employeeMap.insert(std::pair<std::string,EmployeeClass*>(employeeName, &enginerrClassObject));
}

Edit:

Exsample with a reference:

  int main()
    {
        EngineerClass engineerClassObject;
        std:string employeeName = "Peter";
        std::map<std::string employeeName, EmployeeClass&> employeeMap;

        employeeMap.insert(std::pair<std::string,EmployeeClass&>(employeeName, enginerrClassObject));
    }
HWilmer
  • 458
  • 5
  • 14
0

You should store pointers, and they better be smart ones. For example:

std::map<std::string, std::unique_ptr<EmployeeClass>> employeeMap;
employeeMap.insert({"Engineer", std::make_unique<EngineerClass>()});

or

std::map<std::string, std::unique_ptr<EmployeeClass>> employeeMap;
auto engineer = std::make_unique<EngineerClass>()
employeeMap.insert({"Engineer", std::move(engineer)});
Evg
  • 25,259
  • 5
  • 41
  • 83