Search code examples
c++dynamic-cast

Dynamic_cast fails, even though I am(as far as I can tell) definitely casting from a properly-derived class.


So basically I have a class:

class Rigidbody
{
    Collider _collider;
    //blah
}

The Collider class looks like

class Collider
{
    public:
        Collider(Transform trans);
        virtual ~Collider();

        void SetType(const ColliderType newType){_type = newType;}
        const ColliderType GetType(){return _type;}

        void SetTransform(const Transform& trans) { _transform = trans; }
        const Transform& GetTransform() { return _transform; }

    private:
        ColliderType _type;
        Transform _transform;
};

There are a couple of derived classes; for instance:

class CircleCollider : public Collider
{
    public:
        CircleCollider(Transform trans);
        ~CircleCollider();

        const float GetRadius(){return _radius;}
        void SetRadius(const float newRad) { _radius = newRad; }

    private:
        float _radius;
};

In my physics class, basically I have to call the correct collision method, based on which derived classes are colliding (the code for Box vs Circle is different to Circle vs Circle). So I use stuff like

if(CircleCollider* circ1 = dynamic_cast<CircleCollider*>(&bodyA.GetCollider()))
{
    CircleVsCircle(circ1, circ2)
}

etc.

To test this, I create a Rigidbody, then do

CircleCollider coll(player->GetTransform());
coll.SetRadius(10.0f);
player->SetCollider(coll);

So the player's collider should be an instance of CircleCollider. But when I try to dynamic cast it to CircleCollider, the cast fails.

Any ideas why?


Solution

  • I'm just guessing here (since you don't show the GetCollider function), but the GetCollider function returns Rigidbody::_collider then you don't actually have a CircleCollider object, all you have is a Collider object.

    For the polymorphism to work the Rigidbody::_collider needs to be a pointer, and actually initialized to a pointer to a CircleCollider object.

    Related reading: object slicing (it's what happens if you assign a CircleCollider object to the _collider object).