0

I am working on a class project dealing with inheritance. I have a class called Circle that inherits from a class called Shape. When I try to cast a Shape to a Circle I get errors though.

The shape class looks like this

class Shape {
    public:
    Point center;
    string type;
    virtual int area();
};

The circle class like this

class Circle : public Shape {
    public:
    int radius;
    Circle(int x, int y, int r) {
        type = "circle";
        center.x = x;
        center.y = y;
        radius = r;
    }
};

And my code looks like this

int main() {

    std::vector<Shape> shapes;

    Circle c(0, 1, 5);
    shapes.push_back(c);

    for (int i = 0; i < shapes.size(); i++) {
        if (shapes[i].type == "circle") {
            Circle c = (Circle)shapes[i]; // <-- Error line
        }
    }

I cant cast the shape back to a circle but I know it is a circle. I get the

error: no viable conversion from 'std::__1::__vector_base<Shape, std::__1::allocator<Shape> >::value_type' (aka 'Shape') to 'Circle'

What am I doing wrong? Is there a way to force the conversion?

Thank you for any and all help.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

3

Inheritance is an "is-a" relationship, but it's a one-way relationship. Circle "is-a" Shape, but Shape isn't a Circle. That's why you can't cast.

For the casting to work (and to not have slicing) you need to use pointers instead:

std::vector<Shape*> shapes;
shapes.push_back(new Circle(0, 1, 5));
...
Circle* c = static_cast<Circle*>(shapes[i]);

While I showed the above example using standard non-owning pointers, you should really consider using smart pointers, like std::unique_ptr or std::shared_ptr.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621