How to create an array of pointers to object of a inherit class
Consider the following 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
|
class Shape
{
protected:
int length, height;
public:
Shape();
~Shape();
};
class Square : Shape
{
private:
double Area;
public:
Square();
~Square();
};
class Circle : Shape
{
private:
double Circumference;
public:
Circle();
~Circle();
};
|
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
|
int main()
{
Shape *shape[5];
int choice, i = 0;
cout << "Which shape are you making?\n";
cout << "1. Square\n";
cout << "2. Circle\n";
cin >> choice;
if (choice == 1)
{
shape[i] = new Square();
i++;
}
if (choice == 2)
{
shape[i] = new Circle();
i++;
}
}
|
How would I make an array of pointers that contain both Circle and Squares so I can easily access both later to do stuff with it.
Last edited on
Remove lines 15 and 21.
Put lines 7 to 22 within a loop that iterates 5 times
1 2 3 4
|
for (int i = 0; i < 5; i++)
{
// Square/Circle choice code + shape[i] assignment
}
|
And change line 18 to
else if.
Last edited on
Topic archived. No new replies allowed.