How do I loop through a vector of class objects?

For a beginners C++ lab, I have a base class Employee and two derived classes HourlyEmployee and SalaryEmployee. In main, I have a vector defined as vector <Employee *> VEmp; It's then passed to a function to get the input, which works fine. But what I'm struggling with is another function with the header "printList(const vector <Employee *> & Ve)". It's supposed to loop through the vector and call the appropriate printPay function, which is a seperate print function inside each derived class. How do I loop through the vector and print it out? I was trying to do a for loop and something like "Ve[i].printPay();", but that doesn't work. So how would I do it?

Here's some snippets of the relevant code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Employee {
....
	virtual void printPay() = 0;
	

};

class HourlyEmployee : public Employee {
....
	void printPay()
	{
	cout << "The pay is: ";
	}
	
}

class SalariedEmployee : public Employee {
....

	void printPay()
	{
	cout << "The weekly pay is: " << salary/52;
	}
}


int main()
{
	vector <Employee *> VEmp;

	getInput(VEmp);

	printList(VEmp);

	system("pause");
	return 0;
}


void printList(const vector <Employee *> & Ve)
{
for (int i = 0; i < Ve.size(); i++){
Ve[i].printPay();
}
}
You loop through a STL container via an iterator:

1
2
3
4
5
6
7
8
9
10
11
typedef vector<Employee*> V_EMPL;
V_EMPL ve;
... // populate vector etc...

for (V_EMPL::iterator p = ve.begin(); p != ve.end(); ++p)
{
   Employee* pEmployee = *p;

   pEmployee->printpay();

}
line 43 of your code: change Ve[i].printPay() to Ve[i]->printPay()
Someone I know said to create a temporary object and assign its' values. Would that work too? I'm having issues with an access violation with that.

1
2
3
4
5
6
7
8
Employee * obj;
for (int i = 0; i < Ve.size(); i++){
obj = Ve[i];
}

for (int i = 0; i < Ve.size(); i++){
obj[i].printPay();
}
line 43 of your code: change Ve[i].printPay() to Ve[i]->printPay()

THANK YOU! That fixed it!
Topic archived. No new replies allowed.