Shape *shape[100];//global scope
Square sqr;//global scope
void inputdata() {
int len,width;
cout << "enter length";
cin >> len;
cout << "enter width";
cin >> width;
Square sqr(len,width);
shape[0] = &sqr;
//----> if shape[0]->computeArea(); here works fine.
}
void computeArea() {
shape[0]->computeArea(); // --> run fail error
}
Shape is the parent class and square is the sub-class. both have computeArea();
when the code reach computeArea() i am having a weird run fail error. the program just terminate without giving me any errors for me to find and fix it...it just show run fail and stop the program.
the program is able to run properly and show ->computeArea() if the code is within the inputdata() but when i separate it, it just fail to run properly. any solution to this?
This Square
Square sqr(len,width);
is an instance which is local to the scope of inputdata
. Once you leave that scope, you are left with a dangling pointer in shape[0]
. If you want to set the global sqr
, you need
sqr = Square(len,width);
You should find a solution that doesn't rely on global variables though.