How to do this (see post).

Say I created a polygon class. Later, I create classes that are derived from the polygon class.

Now, if I want to create a function which will double de size of each polygon, what should I do?

I know I could do something like:

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
void double_size (square &square) {
square.x=square.x * 2;
square.y=square.y * 2;
}

void double_size (rectangle &rectangle) {
rectangle.x=rectangle.x * 2;
rectangle.y=rectangle.y * 2;
}

void double_size (triangle &triangle) {
triangle.x=triangle.x * 2;
triangle.y=triangle.y * 2;
}

for (x=0; x<square::n; x++) /*n being a static int incrementing each time a new square is created*/
{
double_size (square[x]);
}

for (x=0; x<rectangle::n; x++)
{
double_size (rectangle[x]);
}

for (x=0; x<triangle::n; x++)
{
double_size (triangle[x]);
}


And so on. But is there a way to have all polygon double their size with a single loop? Simething like:

1
2
3
4
for (x=0; x<polygon::n; x++)
{
//What should I write here? Is this even doable? Please help!!
}
Last edited on
Before I start,
for (x=0; x<polygon::n; x++)
This is an extremely unusual construction. You usually don't want to apply a function to all instances of a class, but to some specific subset of them, which may or may not happen to be all of them. For example, this would be much more common:
1
2
3
4
std::vector<polygon> v;
//...
for (size_t a=0;a<v.size();a++)
    //etc. 


Anyway, yes. What you want to do can be done with polymorphism. The code that calls the function would look like this:
1
2
3
4
std::vector<polygon *> v;
//...
for (size_t a=0;a<v.size();a++)
    v[a]->double_size();
polygon would declare double_size() as a pure virtual function:
1
2
3
4
5
class polygon{
//...
    virtual void double_size()=0;
//...
};
Now every class that inherits from polygon would have to implement double_size().
Polymorphism has some subtleties I can't cover here. I recommend checking your book on the subject, if you have one.
Last edited on
Topic archived. No new replies allowed.