I a little bit stack with my exercise, please help. Many thanks in advance.
Wording of assignment:
Polymorphism
Template Method Pattern
In this exercise we are going to create a Print() function that is printing the shape information to the cout object. The Print() function can use the ToString() to obtain the string to print.
You see that the implementation of Print() is in each derived class largely the same; calling ToString() and sending the result to cout. Since the ToString() function is polymorphic, we can use the polymorphic behaviour in the Print() function of Shape.
Thus:
Add a Print() function to the Shape class.
In this function, call the ToString() function and send the result to the cout object.
In the test program, create a point and line object and call the Print() function. Does it print the right information even when point and line do not have the Print() function?
You have now created a function for the base class (Print()) that does all the functionality common to all derived classes. Only the part of that function that is different for each derived class is delegated to a polymorphic function (ToString()). This mechanism is an often used design pattern called “Template Method Pattern”
Sample code that I made :
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <string>
#include <iostream>
using namespace std;
class Shape
{
public:
Shape() {}
virtual void ToString() { cout << " Shape " << endl; }
virtual ~Shape(){ } //!!!!
virtual void Print (Shape* s )
{
s->ToString();
}
};
class Point: public Shape
{
public:
Point() {}
Point(int x, int y): Shape()
{
}
~Point(){} //!!!!
virtual void ToString() { cout << " Point " << endl; }
};
class Line: public Shape
{
public:
Line() {}
Line(string str, const Point& pt1, const Point& pt2): Shape()
{
}
~Line(){} //!!!!
virtual void ToString() { cout << " Line " << endl; }
};
int main()
{
{
Shape* shapes[3]; // Array of pointers to Shape
shapes[0] = new Shape();
shapes[1] = new Line ("line from array ", Point(1,22),Point(33,22));
shapes[2] = new Point(11,44);
cout << "using ToString function" << endl;
shapes[0]->Print(shapes[1]);
for(int i=0; i < 3; i++)
{
delete shapes[i];
}
}
system ("pause");
return 0;
}
|
Also from assingment I don't really understand how I should realize function Print()... In my mind visualize option where I give function Print argument on pointer to Shape* and recall function ToString() with right derived class. However, In my opinion syntax (shapes[0]->Print(shapes[1]) ) looks very weird and unappropriated. May be there are some opportunity realize function like:
I just give argument and function recall me correct answer like :
Print (shape[1]);
...
Before this exercise was one that about ABC may be somehow Print() realize like pure virtual base function, in this case how syntax will be look like ?