I have a base class called Mijloc_transport and 2 derived classes called Masina and Tramvai. I must do an menu type program that can create different kind of objects from the derived classes and show them. I’m using the UPCASTING method and when I press 1 the if(tasta=="1") creates an object and I can see what type it is using: tabp[0]->show();. It seems that when the program enters again in the do loop (using the main label), the object created as 1 is destroyed and I can’t see tabp[0]->show(); because the reference is deleted. What shall I do to keep the objects alive so I can put them in tabp?
Masina b(30);
p=&b;
tabp[i]=p;
so later I can display them….10x for your help
#include "include.hpp"
#include <ctype.h>
#include <cstdlib>
int main(void)
{
int i=0;
Mijloc_transport *tabp[MAX];
Mijloc_transport *p;
int tasta;
main:
do
{
//cout<<"\n\n\n\n\n";
cout<<endl<<"apasa orice tasta pentru a reveni la meniu "<<endl; getch();
system("cls");
cout<<"Tasteaza numarul optiunii dorite din meniu:"<<endl;
cout<<"1. creaza o masina cu 30 cai putere"<<endl; //create an Masina derived Oject
cout<<"2. creaza un tramvai cu 20 de locuri"<<endl;//create an Tramvai derived Oject
cout<<"3. afiseaza memoria"<<endl; //print the objects
cout<<"4. iesire"<<endl;
tasta=cin.get();
}
while(tasta!='1' && tasta!='2'&& tasta!='3'&& tasta!='4');
if(tasta=='1')
{
Masina b(30);
p=&b;
tabp[i]=p;
tabp[0]->show();
cout<<endl<<"apasa orice tasta pentru a reveni la meniu "<<endl;
getch();
//i++; //TREBUIE INCREMENTAT cand ai mai mult de un obiect
goto main;
}
if(tasta=='3')
{
//afiseaza elementele din memorie
//for(int j=0;j<=i;j++) //J<=i
//tabp[j]->show();
tabp[0]->show();
cout<<endl<<"apasa orice tasta pentru a reveni la meniu "<<endl;
getch();
return 1;
}
}
Instead of:
do:
and do not forget to do:
When you no longer need tabp (before existing main).