Christopher Settles
Christopher Settles

Reputation: 413

Overload a function so that it can convert a base class to a derived class as a parameter

I am attempting to model a 3D world, which has objects of spheres and capsules inside of it. I modeled it in a way that the shape class is the base class and that the sphere and capsule classes inherit from the base class (which, if I implemented it correctly, is a perfectly virtual class).

class Shape
{

protected:
    COLORREF color;

public:
    virtual COLORREF getColor() =0;


};


    class Capsule: public Shape
{

private:
    Point start;
    Direction direction;
    int dist, r;
    //Color color;
    //COLORREF color;

public:

    Capsule(Point start, Direction direction, int inputdist, int inputr, COLORREF inputcolor);

    COLORREF getColor();

};

    class Sphere : public Shape
{

private:
    int r;
    Point p;
    //Color color;
    //COLORREF color;

public:
    Sphere(int x, int y, int z , int r, COLORREF inputcolor) ;
    COLORREF getColor();
    Point getpoint();
    int getradius();
};

Then I have a function in a different class that takes in either a pointer to a Sphere object or a pointer to a Capsule object.

bool Collideswith(Sphere *s);
bool Collideswith(Capsule *c);

But I would like to force one of the above functions to be called when i call

Shape *myshape = new Sphere(0,0,0,4, RGB(0,0,0));
 if(myRay.Collideswith(myshape)) { blah... }

But the issue is that since Collideswith only takes in pointers to Capsules or pointers to spheres, when I call it right now it won't take in this pointer to what I'm passing in, which is a pointer to a shape.

I can't change the fact that I'm passing in a shape pointer, but I need to figure out how to have the Collideswith() function take the shape pointer. (Maybe by creating a overloaded function that takes the shape pointer and can figure out if the shape is a capsule or a sphere somehow?)

Any suggestions will be really appreciated. Thanks

Upvotes: 3

Views: 59

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

Declare a virtual method in your Shape class:

class Shape {

// ...

    virtual bool CollidesWith()=0;
};

And implement it in each one of your subclasses:

bool Sphere::CollidesWith()
{
   // ...
}

bool Capsule::CollidesWith()
{
   // ...
}

Now, have each one of these invoke one of those others CollidesWith() methods in that other class you mentioned in your question, simply passing this.

If you feel like it, you can implement another overload:

bool CollidesWith(Shape *s)
{
      return s->CollidesWith();
}

Your virtual method can take any other parameters you need, and forward them, if necessary. For example, your virtual method can take that myRay parameter in your example, and each subclass simply calls myRay, exactly as in your example of your desired code.

Upvotes: 3

Related Questions