Hi, just a quick question (i hope!!), i'm working on an assignment where i need to build a user-defined library of shapes. The class structure is to have "shape" as a base-class with both 2d and 3d shapes as derived classes. I've handled this by storing them in a vector template (though i've omitted this in the code below for simplicity).
One of the main requirements is to pass a 2D shape derived class object (e.g. "circle ci1") as an argument in a generic derived class known as "prism" that will take the area of the 2d shape and allow a depth to be specified to create a prism (for circle->cylinder).
My question is how to pass the derived class object in the prism constructor? I figured i could use a template class to allow for any of the derived class' objects to be passed (though i can restrict to 2d shapes), though i'm not sure as to the syntax to allow for this.
Here's a simplified version of my code (simplified just to illustrate the one area that i'm asking about):
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
const double pi = 3.141592;
class shape
{
public:
virtual double calcarea()=0;
virtual double calcvolume()=0;
virtual string gettype()=0;
virtual bool flat()=0;
virtual ~shape(){}
};
class square : public shape
{
private:
string type;
double length;
string gettype(){return type;}
bool flat(){return true;}
double calcvolume(){return 0;}
public:
square(){type="Square";length=0;}
square(double l){type="Square";length=l;}
double calcarea(){double temp=pow(length,2.);return temp;}
};
class circle : public shape
{
private:
string type;
double radius;
string gettype(){return type;}
bool flat(){return true;}
double calcvolume(){return 0;}
public:
circle(){type="Circle";radius=0;}
circle(double r){type="Circle";radius=r;}
double calcarea(){double temp=pi*pow(radius,2.);return temp;}
};
template <class T> class prism : public shape
{
private:
string type;
double depth;
double basearea;
string gettype(){return type;}
bool flat(){return false;}
double calcarea(){return 0;}
public:
double calcvolume(){double temp=depth*basearea; return temp;}
prism(){type="Prism";depth=0;basearea=0;}
prism(double d, T baseshape){type="Prism";depth=d;basearea=baseshape.calcarea;}
};
int main()
{
circle ci1(2);
prism<circle> pr1(2,ci1);
shape *sh1 = &ci1;
shape *sh2 = &pr1;
cout << sh1->calcarea() << endl;
cout << sh2->calcvolume() << endl;
}
I'm aware that line 63 (and consequently line 69) are both very wrong, but this is where i have no idea what to do. I'll keep trying but if someone could advise me, that would be really helpful.
Thanks!