I want to use inheritance to have an object treated in a different way depending on where in the hierarchy it falls
(similar to this C# question)
Assume you build a hierarchy of Shape objects like:
class Shape {} ;
class Sphere : public Shape {} ;
class Triangle : public Shape {} ; ...
You then equip a Ray class with methods like:
class Ray
{
Intersection intersects( const Sphere * s ) ;
Intersection intersects( const Triangle * t ) ;
};
You store an array of assorted Shape* of various types and call
vector<Shape*> shapes ; ...
//foreach shape..
Intersection int = ray.intersects( shapes[ i ] )
But you get the compiler error
error C2664: 'Intersection Ray::intersects(const Sphere *) const' : cannot convert parameter 1 from 'Shape *const ' to 'const Sphere *'
What did you do wrong?
Is the only way to do it the other way around, with
class Shape
{
virtual Intersection intersects( const Ray* ray )=0 ;
} ;
then each class override intersects? Then calls to
//foreach shape..
Intersection int = shapes[i]->intersects( ray ) ;
Can you do it the first way I showed or NEVER?
You have to do it the other way around. Overload resolution takes place at compile-time, when the type of what you're calling it with is a Shape*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With