I have these two classes below and researcher is deriving from employee. I'm trying to get print to work separately for many different derived employee classes. When I use this method in main below the virtual print function works how I want it to.
Employee* empVec[10];
empVec[0] = new researcher("Hal", "Norman", 40, "ThePhd", "theThesis");
empVec[0]->print();
cout << endl;
empVec[1] = new Employee("Emp", "loyee", 25);
empVec[1]->print();
//TERMINAL
Name: Hal Norman
Salary: $40
PHD: ThePhd
Thesis: theThesis
Name: Emp loyee
Salary: $25
however when i try to use it with a vector it instead gives me this result.
vector<Employee> empVec;
empVec.resize(10);
researcher res("Hal", "Norman", 40, "ThePhd", "theThesis");
empVec[0] = res;
empVec[0].print();
cout << endl;
Employee emp("Emp", "Loyee", 25);
empVec[1] = emp;
empVec[1].print();
//terminal
Name: Hal Norman
Salary: $40
Name: Emp Loyee
Salary: $25
I want to try this project with vectors but I don't know how to do this. Thanks in advance
//EMPLOYEE.H
#ifndef _EMPLOYEE_H_
#define _EMPLOYEE_H_
#include <iostream>
#include <string>
using namespace std;
class Employee
{
public:
string Fname; //First Name
string Lname; //Last Name
int Salary; //Salary
Employee(string Firstname,
string Lastname,
int sal); //Constructor
Employee(); //Constructor
~Employee();
virtual void print();
};
#endif
//RESEARCHER.H
#ifndef _RESEARCHER_H_
#define _RESEARCHER_H_
#include <iostream>
#include <string>
#include "Employee.h"
class researcher :
public Employee
{
public:
researcher(string firstName,
string lastName,
int sal,
string PHD,
string thesis); //constructor
researcher(); //default
~researcher(); //destructor
void print();
private:
string phd;
string phdThesis;
};
#endif
//EMPLOYEE.CPP
#include <iostream>
#include <string>
#include "Employee.h"
Employee::Employee(string FirstName,
string LastName,
int sal)
{
Fname = FirstName;
Lname = LastName;
Salary = sal;
}
Employee::Employee()
{
Fname = "First Name";
Lname = "Last Name";
Salary = 0;
}
Employee::~Employee()
{
}
void Employee::print()
{
cout << "Name: " << Fname << " " << Lname << endl;
cout << "Salary: $" << Salary << endl;
}
//RESEARCHER.cpp
#include "researcher.h"
#include "Employee.h"
#include <iostream>
#include <string>
researcher::researcher(string firstName,
string lastName,
int sal,
string PHD,
string thesis)
: Employee(firstName,
lastName,
sal)
{
phd = PHD;
phdThesis = thesis;
}
researcher::researcher()
{
phd = "PHD";
phdThesis = "Thesis";
}
researcher::~researcher()
{
}
void researcher::print()
{
Employee::print();
cout << "PHD: " << phd << endl;
cout << "Thesis: " << phdThesis << endl;
}