0

Long time since I coded in C++ and I'm getting some error I can't solve:

In the line (take a look at the code snippets): list.push_back(shape)

error: invalid new-expression of abstract class type 'Shape'

But I'm also a bit confused because a bit further up in the compilation log I see:

note: 'virtual bool Shape::hit(const Ray&, float, float, hitRecord&) const' virtual bool hit(const Ray& ray, float tMin, float tMax, hitRecord& hit) const = 0;

I have this abstract class:

#pragma once

#include "Ray.h"

struct hitRecord
{
    float t;
    Vec3 p;
    Vec3 normal;
};

class Shape
{
public:
    virtual bool hit(const Ray& ray, float tMin, float tMax, hitRecord& hit) const = 0;

};

And then two children classes which implement hit:

#pragma once

#include "Shape.h"

class Sphere: public Shape
{
public:
    Vec3 center{};
    float radius{};

    Sphere() = default;

    virtual bool hit(const Ray& ray, float tMin, float tMax, hitRecord& hit) const
    {
        //Do stuff
        return false;
    }
};

And:

#pragma once

#include "Shape.h"
#include <vector>

class ShapeList: public Shape
{
public:
    std::vector<Shape> list;

    ShapeList()
    {
        list = std::vector<Shape>();
    };


    virtual bool hit(const Ray& ray, float tMin, float tMax, hitRecord& hit) const
    {
        // Do Stuff

        return hitAnything;
    }

    void append(Shape& shape)
    {
        list.push_back(shape);
    }
};

Finally in main() I'm basically doing

ShapeList world;
Sphere sphere();
world.append(sphere1);
  • 3
    You can not store ```Shape``` in a Vector because it can not be instantiated. Use ```Shape*``` instead. – Lehks May 16 '19 at 15:52
  • 2
    You'll want to look up object slicing. – George May 16 '19 at 15:52
  • You cannot have a list of abstract class objects directly. For objects to behave polymorphically you need to access them via pointers or references, and `std::vector` doesn't do that. Your list of shapes would have to be `std::vector>` or similar and everything would be fine. – Max Langhof May 16 '19 at 15:53
  • Thanks guys, I was most of the time looking into the second error but it was the first one causing problems... – epsilonmajorquezero May 16 '19 at 16:05
  • 1
    The first one is the `error`, the second one is only a `note` to help you understand the `error` (in this case, why the class is abstract). In a similar situation, it could've been that you forgot (or failed, because of getting the signature wrong,) to override `hit` in `Sphere` so it would still be abstract. In that case trying to create a `Sphere` would give the same error and the note would tell you which pure virtual function you missed. – Max Langhof May 16 '19 at 16:14

0 Answers0