### 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:

 ``1234567891011121314151617181920212223242526272829`` ``````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

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

 ``1234`` ``````for (x=0; x
Last edited on
Before I start,
 for (x=0; 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:
 ``1234`` ``````std::vector v; //... for (size_t a=0;a

Anyway, yes. What you want to do can be done with polymorphism. The code that calls the function would look like this:
 ``1234`` ``````std::vector v; //... for (size_t a=0;adouble_size();``````
polygon would declare double_size() as a pure virtual function:
 ``12345`` ``````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.