user2351750
user2351750

Reputation: 53

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 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?

Upvotes: 0

Views: 60

Answers (3)

Abdullah Shoaib
Abdullah Shoaib

Reputation: 2095

change your code this way:

Shape *shape[100];//global scope
Square *sqr;//global scope  //make it a pointer or reference


void inputdata() {
int len,width;
cout << "enter length";
cin >> len;
cout << "enter width";
cin >> width;
sqr = new Square(len,width);
shape[0] = sqr;   //remove & here
}
void computeArea() {
shape[0]->computeArea(); 
}

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227370

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.

Upvotes: 3

Pete Becker
Pete Becker

Reputation: 76245

Square sqr(len, width) creates an auto object. It goes away when the function returns, even though its address has been stored in shape[0].

Upvotes: 1

Related Questions