Employee listings

Employee listings

Create a base class Employee with the following members: std::string name, std::string position.

Then, create two derived classes Manager and Engineer, both inheriting from Employee.

  1. Manager should have an additional member std::string department
  2. Engineer should have an additional member std::string specialization.

Create a std::vector<Employee*> and populate it with objects of Manager and Engineer. Iterate through the vector and output the name and position of each Employee in the vector using a loop. Remember to initialize the base class attributes in the derived class constructors. Bonus points for being mindful of memory management when creating objects using new.

Answer

#include <iostream>
#include <vector>

struct Employee {
    std::string name;
    std::string position;

    Employee(std::string n, std::string p) : name(n), position(p) {}
};

struct Manager : public Employee {
    std::string department;

    Manager(std::string n, std::string p, std::string d) 
        : Employee(n, p), department(d) {}
};

struct Engineer : public Employee {
    std::string specialization;

    Engineer(std::string n, std::string p, std::string s) 
        : Employee(n, p), specialization(s) {}
};

int main() {
    std::vector<Employee*> employees;

    employees.push_back(new Manager("Alice", "Manager", "Sales"));
    employees.push_back(new Engineer("Bob", "Engineer", "Software"));
    employees.push_back(new Manager("Charlie", "Manager", "HR"));
    employees.push_back(new Engineer("David", "Engineer", "Hardware"));

    for (Employee* employee : employees) {
        // Output only common properties
        std::cout << "Name: " << employee->name << ", Position: " << employee->position << std::endl;
    }

    // Clean up memory
    for (Employee* employee : employees) {
        delete employee;
    }

    return 0;
}
Questions