PHP Code:
#include <iostream>
//forward declerations of derived classes
class Sphere;
class Box;
class Volume //my base class
{
public:
//virtual, non-base-class methods
virtual void checkCollision( const Volume& v ) const = 0;
virtual void checkCollision( const Sphere& s ) const = 0;
virtual void checkCollision( const Box& b ) const = 0;
}
class Sphere : public Volume //derived 1
{
public:
void checkCollision( const Volume& v ) const
{
std::cout << "redo: sphere vs volume" << std::endl;
return v.checkCollision( *this );
}
void checkCollision( const Sphere& s ) const
{
std::cout << "sphere vs sphere" << std::endl;
}
void checkCollision( const Box& b ) const
{
std::cout << "sphere vs box" << std::endl;
}
}
class Box : public Volume //derived 2
{
public:
void checkCollision( const Volume& v ) const
{
std::cout << "redo: box vs volume" << std::endl;
return v.checkCollision( *this );
}
void checkCollision( const Sphere& s ) const
{
std::cout << "box vs sphere" << std::endl;
}
void checkCollision( const Box& b ) const
{
std::cout << "box vs box" << std::endl;
}
}
int main( int argCount , char* args[] )
{
Volume v;
Sphere s;
Box b;
//doesnt work, because of virtual = 0; methods in base class, comment them out then
std::cout << "VOLUME:" << std::endl;
v.checkCollision( v );
v.checkCollision( s );
v.checkCollision( b );
std::cout << "SPHERE:" << std::endl;
s.checkCollision( v );
s.checkCollision( s );
s.checkCollision( b );
std::cout << "BOX:" << std::endl;
b.checkCollision( v );
b.checkCollision( s );
b.checkCollision( b );
}
My understanding of double dispatch, is there an easier and maybe more dynamic method (for adding new derived classes?) without any casting methods?