identifier "poly1" is undefined error
why I'm getting error message :
identifier "poly1" is undefined
in line:
cout<<(poly1==poly2);
why and how to repair it ?
this is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
using namespace std;
class closedPolynom
{..};
class Triangle : public closedPolynom
{..};
class Rectangle : public closedPolynom
{..};
void main()
{
int num;
cin>>num;
if (num==3)
Triangle poly1(num);
else if (num==4)
Rectangle poly1(num);
else
closedPolynom poly1(num);
cin>>num;
if (num==3)
Triangle poly2(num);
else if (num==4)
Rectangle poly2(num);
else
closedPolynom poly2(num);
cout<<endl;
cout<<(poly1==poly2);
}
|
The problem is that if and else statements have their own block scopes. So after executing of if-else was finished defined variables were deleted.
To make it clear the following two statements are equivalent
if (num==3) Triangle poly2(num);
1 2 3 4
|
if (num==3)
{
Triangle poly2(num);
}
|
Last edited on
so, what can I do, if I want to declare on appropiate class type according to user input ?
This
1 2 3 4 5 6
|
if (num==3)
Triangle poly1(num);
else if (num==4)
Rectangle poly1(num);
else
closedPolynom poly1(num);
|
is the same as this
1 2 3 4 5 6 7 8 9 10 11 12
|
if (num==3)
{
Triangle poly1(num);
}
else if (num==4)
{
Rectangle poly1(num);
}
else
{
closedPolynom poly1(num);
}
|
As you see. poly1 will go out of scope on the line after it was created.
If you want to do something like this you should use a pointer to the base class and create the object dynamically.
1 2 3 4 5 6 7
|
closedPolynom* poly1 = 0;
if (num==3)
poly1 = new Triangle(num);
else if (num==4)
poly1 = new Rectangle(num);
else
poly1 = new closedPolynom(num);
|
Don't forget to delete the object when you no longer need it.
delete poly1;
Do the same with poly2.
thanx
Topic archived. No new replies allowed.