Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overload resolution

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?

like image 553
bobobobo Avatar asked Jun 11 '11 16:06

bobobobo


1 Answers

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*.

like image 89
Puppy Avatar answered Oct 15 '22 16:10

Puppy