#include <iostream>

using namespace std;

class BankAccount
{
public:
   BankAccount();
   void deposit(int amount);
   int get_balance() const;
private:
   int balance;
};

BankAccount::BankAccount()
   : balance(0)
{}

void BankAccount::deposit(int amount)
{
   balance = balance + amount;
}

int BankAccount::get_balance() const
{
   return balance;
}

// This function returns a pointer to a new bank account
// However, the account object is allocated on the runtime stack
// of the function. That is an error--the object is deallocated
// as soon as the function exits

BankAccount* make_new_account(int amount)
{

   BankAccount account;
   account.deposit(amount);

   // Here we first put the address of the bank account object
   // into a pointer and then return the pointer. That makes
   // it very difficult for a compiler to issue a warning message

   BankAccount* r = &account;
   return r;
}

int main()
{
   // We call the make_new_account function and print
   // the result.

   BankAccount* harrysAccount = make_new_account(10000);

   cout << "Harry's account: " << harrysAccount->get_balance() << endl;

   // Now we call the make_new_account function a second time

   BankAccount* sallysAccount = make_new_account(20000);

   // Finally we print both balances

   cout << "Harry's account: " << harrysAccount->get_balance() << endl;
   cout << "Sally's account: " << sallysAccount->get_balance() << endl;
   return 0;
}

/*

Output:

Harry's account: 10000
Harry's account: 20000
Sally's account: 4272164

Explanation:

The first output line makes it appear as if this code actually
works correctly.

The second output line shows that the stack memory is simply
reused when the make_new_function is called twice in a row. 
Afterwards, both pointers actually point to the same memory 
location.

The third output line shows that the other function calls (to 
the get_balance and output functions) overwrite the runtime stack
with their own variables, thereby clobbering the bank account 
object

 */
