Class pointer problem
What's wrong with my code?
I create the vector<Employ*> v. The v[0]->calcSalary() should be 500 but it was a wrong number 687194768.
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
|
#include<iostream>
#include<algorithm>
#include<vector>
#include<iterator>
using namespace std;
class Employee{
int _hours;
int _hourlyPay;
public:
Employee(int hours, int hourlyPay) :_hours(hours), _hourlyPay(hourlyPay){}
int calcSalary(){ return _hours*_hourlyPay; }
};
class EmployeeGen{
public:
Employee* operator()(){
Employee a(10, 50);
return &a;
}
};
int main(){
vector<Employee*> v;
generate_n(back_inserter(v), 10, EmployeeGen());
cout<<v[0]->calcSalary();
}
|
Thank you
You can't return a pointer to a local from a function. You need to dynamically allocate your Employees. E.g. new Employee(10, 50)
Thank you helios
Topic archived. No new replies allowed.