Problem with object going out of scope.

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.

Thank you.


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
  #include <iostream>
#include "certificateOfDeposit.h"


certificateOfDeposit *ptrCD;

bool cdOperations(certificateOfDeposit &objCD)
{
	cout << "Your account number is -->" << objCD.getAccountNumber() << endl;
					 

	return true;
}

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.
Last edited on
Thanks so much Yanson!! This did it!

ptrCD = new certificateOfDeposit(objCD);

I will need to do a

 
delete ptrCD;


whenever I finish using this pointer, probably in my delete account function.
Topic archived. No new replies allowed.