I am writing a program for a school that uses derived classes of an abstract class named bankAccount.
I am running into a problem with the design of my program where menus are concerned. I have really simplified what is happening in the menu system with the code below. The problem I am having is that I am going out of scope when creating my object of type certificateOfDeposit.
I need a way to save this, as I will have a choice in a menu to return to the cdOperations menu. I would rather not use file I/O in this case.
#include <iostream>
#include "certificateOfDeposit.h"
certificateOfDeposit *ptrCD;
bool cdOperations(certificateOfDeposit &objCD)
{
cout << "Your account number is -->" << objCD.getAccountNumber() << endl;
returntrue;
}
void andAnotherMenu()
{
// process my pointer
// PROBLEM my pointer loses it's values even though I declared global??
cdOperations(*ptrCD); // dereferenced memory location of the object that was pointed to
}
void createAccount()
{
// simple create an account
certificateOfDeposit objCD("Jane", "Doe", 100.00, 3, .02, 2);
//create a pointer to the object I just created
ptrCD = &objCD;
// do some operation
cdOperations(objCD);
}
int main()
{
createAccount();
// do something elsewhere
andAnotherMenu();
return 0;
}
the object you create on line 28 has local scope. So it is destroyed when the function ends. The first call to cdOperations succeeds because it is called from within your createaccounts function. Meaning the object objCD hasn't beed destroyed yet. When you call andAnotherMenu from main the object has been destroyed. It dosn't matter that your pointer is global because it is pointing to an object with local scope. you could try using the new keyword because an object created with the new keyword won't be destroyed until you call delete.