I am working on an assignment about pure virtual functions. I have two different classes that i wish to use a pure virtual function. The virtual function is used to calculate area, each class i.e ( square, triangle) use different arguments to calculate the area. How can i make both getArea functions work with the pure virtual function?
#include <iostream>
#include <cmath>
using namespace std;
class Point{
public:
double x, y;
Point(double a = 0, double b = 0){x = a; y = b;}
Point operator + (Point const &obj){
Point p;
p.x = x + obj.x;
p.y = y + obj.y;
return p;
}
Point operator - (Point const &obj){
Point p;
p.x = x - obj.x;
p.y = y - obj.y;
return p;
}
friend ostream& operator<<(ostream& os, const Point& pt);
};
class Shape{
public:
virtual double getArea(Point a, Point b, Point c, Point d) = 0 ; // this is where i have a problem
// need this to be virtual void getArea() = 0; so i can use it for every other class but not sure how
};
class Square: public Shape{
public:
// find area from four points
double length(Point a, Point b){
double hDis = pow((b.x - a.x),2);
double vDis = pow((b.y - a.y),2);
return sqrt(hDis + vDis);
}
double area_triangle(Point a, Point b, Point c){
double A = length(a, b);
double B = length (b, c);
double C = length(a, c);
double S = (length(a, b) + length (b, c) + length(a, c))/2;
double area = sqrt((S*(S-A)*(S-B)*(S-C)));
return area;
}
double getArea(Point a, Point b, Point c, Point d){ // have to calculate area with the point coordinates
double area_tri1 = area_triangle(a, b, c);
double area_tri2 = area_triangle(a, d, c);
double total_area = area_tri1 + area_tri2;
return total_area;
}
};
class Triangle: public Shape{
public:
double length(Point a, Point b){
double hDis = pow((b.x - a.x),2);
double vDis = pow((b.y - a.y),2);
return sqrt(hDis + vDis);
}
double getArea(Point a, Point b, Point c){
double A = length(a, b);
double B = length (b, c);
double C = length(a, c);
double S = (length(a, b) + length (b, c) + length(a, c))/2;
double air = sqrt((S*(S-A)*(S-B)*(S-C)));
return air;
}
};
ostream& operator<<(ostream& os, const Point& pt)
{
os << pt.x << ", " << pt.y <<endl;
return os;
}
int main(){
Point p1(5,-5), p2(-10,7), p3(4, 23), p4(-6, 12);
Square s;
cout << s.getArea(p1, p2, p3, p4);
//! Triangle t;
//! cout << t.getArea(p1, p2,p3);
// this gives me an error because the abstract function want
// (Point a, Point b, Point c, Point d)
// how do i make this work?
}
Shapeshouldn't know or care if what is derived needs 2, 3, 4, 5, or 100 points to calculate the area. Those items should be known by the derived class, notShape. On the other hand, your design would be perfect if on purpose, you only wanted derived shapes that took exactly 4 points to define the area. The compiler did its job, and that is to error out because yourTriangleviolated the restrictions of how to compute the area.