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
.
Polymorphism only works with non-value types; i.e. with references and pointers. And since references must be immediately bound they are not much use here.
Your best bet is to use
std::unique_ptr<Shape> poly(new Polygon());
and call usingpoly->getType();
I'm using
std::unique_ptr
so I don't need to calldelete
explicitly.std::shared_ptr
would work too but do consult the documentation so you use the one most appropriate to your use case.By the way, you don't need to repeat
virtual
when overriding the function in child classes. You only need to mark the functionvirtual
in the base class.