class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtualint area (void) =0;
};
class CRectangle: public CPolygon {
public:
int area (void)
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area (void)
{ return (width * height / 2); }
};
Both of the area functions are of type int; and the virtual function is of the same type - no issue.
But say each object had co-ordinates for each vertex defining the shape and you wanted a virtual translate function - is it possible to return a different type dependant on when the function is called (for example; CTriangle.translate() would return a CTriangle object, CRectangle.translate would return a CRectangle object, etc.)?
My initial plan was to store the result of the translation as a different object - so the user can see the coordinates before and after the operation.
So loosely speaking:
CTriangle Triangle - co-ordinates (0, 0), (1,0), (0, 1)
[Rotate 90 degrees counter clockwise about origin]
CTriangle Triangle_Res - co-ordinates (0, 0), (0,1), (-1, 0)
Where Triangle and Triangle_Res are two different instances of CTriangle.
This can't be done easily using Virtual functions, but by making it a void function which prints the coordinates after performing the necessary actions i.e.
Triangle - co-ordinates (0, 0), (1,0), (0, 1)
[Rotate 90 degrees counter clockwise about origin]
Output co-ordinates (0, 0), (0,1), (-1, 0)
Here only Triangle is an object belonging to CTriangle - the output coordinates either replace Triangles coordinates, or they are just printed to the screen (Guessing this is what you were thinking when you asked why return anything?)
Converting to the second case shouldn't be too much work; I'll just amend to allow that.
the clean way is to use a template function, if you intend to return the same type back from the transformation (due to the fact that the same transformation algorithm applies to all CPolygon, regardless of how many vertices you have, and yet, you want to maintain the original type).
technically, you could achieve the same result using virtual functions, but then you would have to downcast to get your original type back and downcasting is not a good thing (you could also make CRectangle, CTriangle call the common transformation function, but that results in a lot of boilerplate code).
conclusion: template functions are cleanest
here is a working example of a flip about the y-axis that you can easily adapt for your rotation
Something that throws me a bit about that piece of code is the size_t type declaration used there - couldn't see a definition, but from what I can gather it can be replaced with int with no loss of data.
Is there a particular reason it was chosen over int?