c++ - object inheritance virtual function run fail error -


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 parent class , square sub-class. both have computearea();

when code reach computearea() having weird run fail error. program terminate without giving me errors me find , fix it...it show run fail , stop program.

the program able run , show ->computearea() if code within inputdata() when separate it, fail run properly. solution this?

this square

square sqr(len,width); 

is instance local scope of inputdata. once leave scope, left dangling pointer in shape[0]. if want set global sqr, need

sqr = square(len,width); 

you should find solution doesn't rely on global variables though.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -