Search code examples
c++inheritanceabstract-classoverridingpure-virtual

Iterating through vector of abstract classes


There is already a similar question, but it did not answer my question so I'll ask again.

I have this classes:

#ifndef _OBJECTS_H
#define _OBJECTS_H

#include "ray.h"
#include <cmath>

class Object {
    public:
        Vector3 position, color;
        Object(Vector3 position, Vector3 color): position(position), color(color){};

        virtual bool intersects() = 0;
};

class Sphere : public Object {
    public:
        float radius;
        Sphere(Vector3 center, float radius, Vector3 color): Object(center, color), radius(radius){};

        using Object::intersects;
        bool intersects(const Ray& ray, float& t);
};

#endif

and I need to have std::vector of objects and iterate through it:

for(Object s:objects) {
                float t;
                if (s.intersects(ray, t)) {
                    //do something
                }
            }

When I declare intersects() as pure virtual, then it tells me that I can't iterate through virtual class, if I declare it only as virtual then it tells me intersects is not implemented. What am I doing wrong?


Solution

  • As (by definition) you can't create instances of abstract classes, a std::vector<> can't contain instances of abstract classes. You need to change your container to contain pointers. Then the pointer type can be a pointer to an abstract class.