I know what are pointer's and how to you them but there is one point i am not able to understand. Below is the example code
I understand everything in the below code except 1 thing why i am using pointer to base class object in vector int the main() Function?
Code:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
// base class
class Employee {
protected:
string name;
double pay;
public:
Employee() {
name = "";
pay = 0;
}
Employee(string empName, double payRate) {
name = empName;
pay = payRate;
}
string getName() const {
return name;
}
void setName(string empName) {
name = empName;
}
int getPay() {
return pay;
}
void setPay(int payRate) {
pay = payRate;
}
string toString() {
stringstream stm;
stm << name << ": " << pay;
return stm.str();
}
virtual double grossPay(int hours) {
return pay * hours;
}
};
// derived class
class Manager : public Employee {
private:
bool salaried;
public:
Manager(string name, double pay, bool isSalaried)
: Employee(name, pay)
{
salaried = isSalaried;
}
bool getSalaried() {
return salaried;
}
virtual double grossPay(int hours) {
if (salaried) {
return pay;
} else {
return pay * hours;
}
}
string toString() {
stringstream stm;
string salary;
if (salaried) {
salary = "Salaried";
} else {
salary = "Hourly";
}
stm << name << ": " << pay
<< ": " << salary << endl;
return stm.str();
}
};
int main()
{
Employee emp1("Jones", 25.00);
Manager mgr1("Smith", 1200, true);
vector<Employee*> employees;
employees.push_back(&emp1);
employees.push_back(&mgr1);
for (int i = 0; i < employees.size(); ++i) {
cout << "Name: " << employees[i]->getName()
<< endl;
cout << "Pay: " << employees[i]->grossPay(40)
<< endl;
}
return 0;
}
Here is the lines of code i want to understand.
Code:
vector<Employee*> employees;
employees.push_back(&emp1);
employees.push_back(&mgr1);
I know if i will not use the pointer base class function "virtual double grossPay" will be called for both base class object and derived class object and when i will use pointer with reference to the object because base class function is virtual it will look for same function in derived class and if available it will execute it.
I think my concept about pointers is not clear any help to understand this will be highly appreciated.
Sorry for my english but i think i explain my point.