How do I use my class shape as shown below? Class shape is one that consist of the draw method. But how do I show the inheritance from Class shape to class polygon then to class Line? Thanks in advance!
First, you seem to have confused what a Polygon is with what a Point is. Your "Polygon" class contains an x value and a y value. Your "Polygon" is quite clearly not a polygon - it's a point.
But how do I show the inheritance from Class shape to class polygon then to class Line?
I don't understand the question. Show? Show to whom? Your code already shows the inhertiance. We can look at the code and clearly see that Line inherits from Polygon, and clearly see that Polygon inherits from Shape.
#include <vector>
class Point
{
private:
int x;
int y;
public:
Point() : x(0), y(0) {}
Point(int x, int y) : x(x), y(y) {}
};
// Shape is pure abstract
// https://en.wikibooks.org/wiki/C%2B%2B_Programming/Classes/Abstract_Classes/Pure_Abstract_Classesclass Shape
{
public:
virtualvoid Draw() = 0;
};
// This is just abstract
// Some things are virtual, and other things are concrete.
class Polygon : public Shape {
private:
std::vector<Point> points;
public:
Polygon(int n) {
points.resize(n);
}
virtualvoid Draw() = 0;
};
// This is a real thing
class Line : public Polygon {
public:
// A line is a Polygon with 2 points
Line() : Polygon(2) {
}
// And is actually drawable
void Draw ( ) {
}
};
#include <vector>
class Point
{
private:
int x;
int y;
public:
Point():x(0), y(0) { }
Point(int x, int y):x(x), y(y) { }
// Helper function. Draw a line between this point and another
drawLine(const Point &other);
};
// Shape is pure abstract
// https://en.wikibooks.org/wiki/C%2B%2B_Programming/Classes/Abstract_Classes/Pure_Abstract_Classesclass Shape
{
public:
virtualvoid Draw() = 0;
};
class Polygon:public Shape
{
private:
std::vector < Point > points;
public:
Polygon(int n)
{
points.resize(n);
}
void Draw(); // connect points[0] to points[1] to ... to points[n] back to points[0]
};
// This is a real thing
class Line:public Shape
{
public:
Point points[2];
void Draw() { points[0].lineTo(points[1]); }
};
For simple school exercises, you could probably get away with Point points[10];
Ask your teacher what an acceptable number of points in a polygon is.
If it really does need to vary, then
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Polygon:public Shape
{
private:
Point *points;
public:
Polygon(int n)
{
points = new Points[n];
}
virtual ~Polygon() // must be virtual when inheritance is possible
{
delete [] points;
}
void Draw(); // connect points[0] to points[1] to ... to points[n] back to points[0]
};