Re: API for intersection.
 
Victor Bogado wrote:
I want to create a program that has an "element" class, the element is
a graphic object that has a finite shape. It goes some what like
this :
class Element
{
[..]
// naive implementation
bool intersect(Element &e)
{
return distance(*this) < radius() + e.radius();
}
};
Now suppose I have a decedent class that holds a "circle element" and
another that holds a "square element", how do I make a smarter
intersect that compares both of them? [..] How this is done usually?
Read about "double dispatch".  You will most likely have to make your
'Element' aware of all descendants, and then implement No-Op functions
that would 'intersect' the 'Element' with any of those.  And then make
the descendants implement those they know about in a funny redirected
way:
    class Element { // Circle Square Triangle will derive
    public:
        virtual bool intersectCircle(Element&) { return false; }
        virtual bool intersectSquare(Element&) { return false; }
        virtual bool intersectCircle(Element&) { return false; }
        virtual bool intersect(Element&) = 0;
    };
    class Circle : public Element {
    public:
        virtual bool intersectCircle(Element&);
        virtual bool intersectSquare(Element&);
        virtual bool intersectCircle(Element&);
        virtual bool intersect(Element& e) {
            return e.intersectCircle(*this);
        }
    };
    class Square : public Element {
    public:
        virtual bool intersectCircle(Element&);
        virtual bool intersectSquare(Element&);
        virtual bool intersectCircle(Element&);
        virtual bool intersect(Element& e) {
            return e.intersectSquare(*this);
        }
    };
    class Triangle : public Element {
    public:
        virtual bool intersectCircle(Element&);
        virtual bool intersectSquare(Element&);
        virtual bool intersectCircle(Element&);
        virtual bool intersect(Element& e) {
            return e.intersectTriangle(*this);
        }
    };
The other functions implement as intended/required.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask