I have to classes, one Employee
class and one BankAccount
class, the employee class has the BankAccount
class as a private variable pointer.
This is what I am trying to do:
- I need to set up all the
BankAccount
s in eachEmployee
with values - then I delete all
BankAccounts
for everyEmployee
at the end of the function.
I use a member function setter in Employee
to set up the BankAccount
pointer. BankAccount
has one private variable and that is amount. Later I call delete on a pointer that should point to each BankAccount's
memory address. After I call print to see the values of the bank for each Employee
and it is still printing values for each BankAccount
If I call delete shouldn't the memory on heap be delete and when print is called not output anything for BankAccount
?
Here is the code:
vector<Employee*> employees;
//get employee full name & salary and return
employees.push_back(get_employee_info());
//setup their bank account
setup_bank(employees);
//make temp pointer to store bank memory address
BankAccount * tempBankPtr;
for (int i =0; i < employees.size(); i++) {
tempBankPtr =employees[i]->get_bank();
delete tempBankPtr // delete the heap object that pointer is pointing at
}
//print values
for (int i =0; i< employees.size(); i++) {
employees[i]->print();
}
code for print
void Employee:: print() const {
cout << "First name is: " << firstName << "\n";
cout << "Last name is: " << lastName << "\n";
BankAccount* bankholder = NULL;
bankholder = get_bank();
if(bankholder != NULL)
cout << "Account Balance is: " << get_bank()->get_amount() << "\n"; //prints values
}
getter for bank
BankAccount* Employee::get_bank() const{
return bank;
}
this is called in setup_bank
void Employee::set_bank(Employee* e, double amount){
bank = new BankAccount(amount);
}