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

1
  • From the code you've posted, I don't see a problem, you probably have wrong things elsewhere. Commented May 8, 2013 at 13:32

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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].

Comments

0

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(); 
}

4 Comments

There's no need for this dynamic allocation.
@juanchopanza What's the problem in dynamic allocation?
There is no need for it, so why use it? Now you have a resource you need to keep track of and delete.
@juanchopanza okay got it. Keeping track of it and deleting it convinces me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.