I have a virtual base class Shape
:
class Shape {
public:
virtual bool intersect(Ray& r, HitRecord& rec)=0;
virtual Material material()=0;
};
I think its the so called "pure virtual" class. So I think I should not try to instantiate it at any time.
However, I have a struct HitRecord
which stores a pointer to the subclasses of Shape
and since I don't know what class exactly does this pointer points to, I define it by Shape*
:
struct HitRecord {
float t;
vec3f p; // point coord
vec3f norm;
Shape* obj;
};
I'm actually trying to build a ray tracer, so I have a intersect()
to check if rays intersect shapes. And if the ray do not intersect any shape in the scene, the rec
variable will no be changed, i.e. rec.obj
is pointing to a Shape
.
So every time this happens I will get a BAD_ACCESS
error since **I want to access a member variable of rec.obj
. It should work when rec.obj
is pointing to a subclass of Shape
, but not when it's pointing to Shape
.
bool intersect(Ray& r, HitRecord& rec) {
rec.t = 100;
for (std::vector<Shape* >::iterator it = shapes.begin(); it != shapes.end(); ++it) {
HitRecord tmpRec;
if ((*it)->intersect(r, tmpRec) && tmpRec.t < rec.t) {
rec = tmpRec;
}
}
}
So now I want to check if the pointer is pointing to the exact Shape
base class. I tried dynamic_cast
but is seems it's not for this kind of situation.
I was wondering if this is a "design problem" or not. If not, how do I check the pointer is pointing to Shape
?