Consider the abstract class declaration:
class aPolygon
{
protected:
long double * sides, // There are N sides with different lengths
* angles; // There are N angles with different sizes
long int no_of_sides; // The number of sides, N, of this polygon
public: aPolygon(long int _sides = 1);
/* It sets no_of_sides = _sides.*/
virtual void input () = 0; // input the derived polygon
virtual void display () = 0; // display the derived polygon
~aPolygon() {}
};
Write a complete C++ class implementation of the following derived class, aSquare, with the class interface::
class aSquare : public aPolygon
{
public:
aSquare(); /* It creates a square as a unit square */
~aSquare() {}
virtual void input(); /* It inputs the data for the square */
virtual void display(); /* It displays the square: angles, sides, perimeter and area */
long double perimeter(); /* It computes the perimeter of the square */
long double area(); /* It computes the area of the square: */
};
#include <iostream>
using namespace std;
class aPolygon
{
protected:
long double * sides, // There are N sides with different lengths
* angles; // There are N angles with different sizes
long int no_of_sides; // The number of sides, N, of this polygon
public:
aPolygon(long int _sides = 1);
/* It sets no_of_sides = _sides.*/
virtual void input () = 0; // input the derived polygon
virtual void display () = 0; // display the derived polygon
~aPolygon();
};
aPolygon::aPolygon(long int _sides)
{
no_of_sides = _sides;
sides = new long double[no_of_sides];
angles = new long double[no_of_sides];
}
aPolygon::~aPolygon() {
delete [] sides;
delete [] angles;
}
class aSquare : public aPolygon
{
public:
aSquare(); /* It creates a square as a unit square */
~aSquare() {}
virtual void input(); /* It inputs the data for the square */
virtual void display(); /* It displays the square: angles, sides, perimeter and area */
long double perimeter(); /* It computes the perimeter of the square */
long double area(); /* It computes the area of the square: */
};
aSquare::aSquare() : aPolygon(4)
{
for (int i=0; i<4; i++) {
sides[i] = 1.0;
angles[i] = 90;
}
}
void aSquare::input()
{
cout << "Enter a side length of a square: ";
long double a;
cin >> a;
for (int i=0; i<4; i++) {
sides[i] = a;
}
}
void aSquare::display()
{
cout << "Square: sides = " << sides[0] << "; angles = "
<< angles[0] << " deg" << endl;
}
long double aSquare::perimeter() {
return 4 * sides[0];
}
long double aSquare::area() {
return sides[0] * sides[0];
}
int main() {
aSquare sq;
sq.input();
cout << endl;
sq.display();
cout << "Perimeter = " << sq.perimeter() << endl;
cout << "Area = " << sq.area() << endl;
return 0;
}
Comments
Leave a comment