I want users of my class "ShapeHolder" to be able to set the "Shape shape" member variable to be any class with the same interface (int w/h, getArea(), etc). Therefore, I believe I made the base class an abstract class by setting a function to virtual (?), and added derived classes to act as the various implementations of shape.
However, this current code throws an error where the Shape shape member variable is defined, saying that I "cannot declare field 'ShapeHolder::shape' to be of abstract type 'Shape'".
In the perfect world, I would love the user to be able to hand in the enum corresponding to the class they want to be represented by the Shape member variable. Is there a way to do this?
Is there a better method all together than the base:derived class interface I am trying to create here?
I have the following example program to illustrate my question:
#include <iostream>
#include <string>
using namespace std;
typedef int shape_type;
enum {SQUARE, TRIANGLE, REGTANGLE};
// Base class
class Shape {
public:
Shape(int h, int w){
height = h;
width = w;
};
virtual int getArea() = 0;
//int getArea(){return -999;};
private:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape {
public:
Rectangle(int h, int w) : Shape(h, w){
height = h;
width = w;
};
int getArea() {
return (width * height);
}
private:
int height;
int width;
};
class Triangle: public Shape {
public:
Triangle(int h, int w) : Shape(h, w){
height = h;
width = w;
};
int getArea() {
return (width * height)/2;
}
private:
int height;
int width;
};
// Main Class
class ShapeHolder {
public:
ShapeHolder(int ver, string s, shape_type st):
dummyInt(ver), dummyString(s), shape(ver, ver){};
void printStuff(){
cout << shape.getArea() << endl;
}
private:
int dummyInt;
string dummyString;
// this type should be dependent on shape_type
Shape shape;
};
int main() {
ShapeHolder sh(10, "test", TRIANGLE);
sh.printStuff();
return 0;
}