So I have this code where a PiggyBank object is created. There are three if statements depending on a choice. Since the keyword new allocates the object in the heap how should I properly manage the memory garbage,so when a different type of constructor is created, the old piggy bank will disappear, in the following code:
while(fChoice!=""){
showFunctions();
PiggyBank *pb;
cin>>fChoice;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(fChoice=="a") {
pb = new PiggyBank();
}
else if (fChoice=="b"){
cout<<"ENTER NAME:"<<endl;
string name = "";
cin>>name;
pb = new PiggyBank(name);
}
else if (fChoice=="c") {
cout<<"ENTER NAME:"<<endl;
string name = "";
cin>>name;
cout<<"ENTER STARTING BALANCE:"<<endl;
int startBalance = 0;
cin>>startBalance;
pb = new PiggyBank(name,startBalance);
}
}
Don't use dynamic memory allocation in the first place. There is no apparent reason for it here:
while(fChoice!=""){
showFunctions();
PiggyBank pb;
cin>>fChoice;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(fChoice=="a") {
pb = PiggyBank();
}
else if (fChoice=="b"){
cout<<"ENTER NAME:"<<endl;
string name = "";
cin>>name;
pb = PiggyBank(name);
}
else if (fChoice=="c") {
cout<<"ENTER NAME:"<<endl;
string name = "";
cin>>name;
cout<<"ENTER STARTING BALANCE:"<<endl;
int startBalance = 0;
cin>>startBalance;
pb = PiggyBank(name,startBalance);
}
}
(of course there is some dependence on the definition of PiggyBank
here)
If you need to allocate dynamically (and you better have a very good reason for it), use std::unique_ptr
which is a smart pointer that handles the deletion automatically for you when it goes out-of-scope or is assigned a new pointer.
while(fChoice!=""){
showFunctions();
std::unique_ptr<PiggyBank> pb;
cin>>fChoice;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(fChoice=="a") {
pb = new PiggyBank();
}
else if (fChoice=="b"){
cout<<"ENTER NAME:"<<endl;
string name = "";
cin>>name;
pb = new PiggyBank(name);
}
else if (fChoice=="c") {
cout<<"ENTER NAME:"<<endl;
string name = "";
cin>>name;
cout<<"ENTER STARTING BALANCE:"<<endl;
int startBalance = 0;
cin>>startBalance;
pb = new PiggyBank(name,startBalance);
}
}
(requires #include<memory>
)