I was asked to implement this chart in polymorphism, which the output is to calculate geometry:
The criteria is as follows:
- print() and getArea() function are placed in base class, which is Shape. It is also asked that it's a pure virtual function but I'm starting to doubt it(..?)
- getPerimeter() function is placed in 2d class, and getVolume() is placed in 3d class
- Each child of dimension shape has getArea() and getPerimeter() or getVolume(), depends on the dimension, which its function is to calculate
Here's the snippet of what I've done. To shorten, I'll put 2d class as an example:
//base initiation
class Shape{
public:
virtual void print(){};
virtual void getArea(double n){};
};
//2d class which is derived from base class
class TwoDimensionalShape : public Shape{
public:
virtual void getPerimeter(double n){};
};
//The actual shape
class Circle : public TwoDimensionalShape{
protected:
double perimeter, area;
public:
void getArea(double radius){
this->area=(3.1415*radius*radius);
}
void getPerimeter(double radius){
this->perimeter=(3.1415*2*radius);
}
void print(){
cout << "Circle's perimeter: " << this->perimeter << endl;
cout << "Circle's area: " << this->area << endl;
}
Circle(){};
~Circle(){};
};
And for the usage itself is:
//setting the object as global
Shape *object;
//the class
void circle(){
Circle circle;
object=&circle;
double radius;
system("cls");
do{
cout << "Enter radius value: ";
cin >> radius; flush();
} while (radius<=0);
object->getPerimeter(radius); object->getArea(radius);
object->print(); cin.get();
}
And I think I did it okay, but not! The error list shows:
Error 4 error C2039: 'getPerimeter' : is not a member of 'Shape'
Error 5 IntelliSense: class "Shape" has no member "getPerimeter"
I was thinking about using cast, but I plainly have no experience with it.
Long story short, how do I able to access any kind of derived class only by using Shape *object (This object is also used for sphere, cube, tetrahedron, etc)?
p.s. this is not a duplicate of What should the TwoDimensionalShape Class contain? as it asks a totally different thing
EDIT 1: Yeah the signatures suck so I will edit my code in my desktop later as well as this one so please continue. Thanks!