I have tried to make the following test program work for 2 days now,however its not working. It is based on several header files which work completely fine, because I checked them via another testprogram. It has header files called Area,Circle,Ring,Rectangle and Square. Also I defined function randcolor and randsize; I checked everyhting over and over, however it is producing the same ouptut aftera second try in the while loop:
int main()
{
srand(time(NULL));
Area *list[20];
int m;
Area *c;
int j = 0;
while (j < 20) {
m = rand() % 4;
cout << m << endl;
switch (m) {
case 0: {
Circle a(randcolor(), randsize());
c = &a;
break;
}
case 1: {
Ring r(randcolor(), randsize(), randsize());
c = &r;
break;
}
case 2: {
Rectangle re(randcolor(), randsize(), randsize());
c = &re;
break;
}
case 3: {
Square sq(randcolor(), randsize());
c = &sq;
break;
}
}
list[j] = c;
j++;
}
return 0;
}
Please help me Expected output should be like: 2 Area constructor is called.. 1 Area constructor is called 0 Area constructor is called
So it should be like: 20 times randomnumber between 0 and 3 "Area constructor is called..."
But it is giving the same number after the second try... in while loop
case 0for example. as soon as the break hits, scope is left andais destroyed, leavingcas an indeterminate pointer. Adding that to your array is icing on that UB cake.on the stackgets destroyed as soon as it leaves that scope. IE:if (...) {object();}Object will be destroyed as soon as it hits the second brace..if(...) Object();Object is destroyed right after theif statementis ran. See here: stackoverflow.com/questions/10080935/…