I have a class defined like this:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class Shape {
protected:
float width, height;
public:
virtual ~Shape(){}
void set_data (float a, float b){
width = a;
height = b;
}
virtual string getType() {
return "Shapes";
}
};
class Polygon: public Shape {
public:
virtual ~Polygon(){};
virtual string getType() {
return "Polygon";
}
};
class Triangle: public Polygon {
public:
virtual ~Triangle(){};
virtual string getType() {
return "Triangle";
}
};
And I want to get a program that uses this class
int main () {
Shape poly = Polygon();
Shape tri = Triangle();
std::cout << poly.getType() << std::endl;
std::cout << tri.getType() << std::endl;
return 0;
}
Is there a way to get poly.getType()
to print out Polygon
, for example? Right now it is printing out Shapes
. I know if I did
Polygon poly = Polygon()
that does the trick, but I want to store poly
as a Shape
object, construct it using a Polygon
constructor, and ensure that
poly.getType()
returns Polygon
, not Shapes
.