The more I research this problem, the more confused I seem to be getting. This is a homework problem which involves augmenting code given us by our professor. I know the problem has to do with the const keyword, and some very confusing new applications of it.
There is a generic class, Object, from which several subclasses (Sphere, Cone, Polygon) inherit. Here are the classes in Object:
public: // computational members
// return t for closest intersection with ray
virtual float intersect(const Ray &ray) const = 0;
// return color for intersection at t along ray r
virtual const Vec3 appearance(const World &w,
const Ray &r, float t) const = 0;
//The following function is added by me
virtual const Vec3 normal(Vec3 p);
};
I added the final function, normal.
So within, for instance, the Sphere class, this is implemented thusly:
const Vec3 Sphere::normal(Vec3 p)
{
return (p - d_center).normalize();
}
When I `make’, I get the following error:
Appearance.cpp: In member function ‘const Vec3 Appearance::eval(const World&, const Vec3&, const Vec3&, Vec3, int) const’:
Appearance.cpp:46: error: passing ‘const Object’ as ‘this’ argument of ‘virtual const Vec3 Object::normal(Vec3)’ discards qualifiers
make: *** [Appearance.o] Error 1
Can you help me understand why this is happening? Thanks for your help.
When the error-message refers to the
‘this’ argumentof a method, it means (a pointer to) the object that you’re calling the method on. For example, inshape->normal(v),shapeis thethisargument.To specify that a given method doesn’t modify its own object — its
thisargument — you need to appendconstto its declaration. So, change this:to this:
to indicate that it’s “safe” to call
normal(...)on aconstobject.Similarly, change this:
to this: