Overloading inherited function

I trying to building a game engine using c++ and SFML library. I am working on collision detection. I created a base class Collider that has a pure virtual function collideWith(Collider* other). I would like to inherit that into BoxCollider and CircleCollider, where I would like to overload the collideWith(Collider* other) to distinguish different types of colliders and respond accordingly. I am doing that to be able to create a std::list<Collider*> in the game class and use polymorphism and overloading to check for proper collision. The only way I was able to accomplish this was to override the collideWith(Collider* other) function in derived classes, use dynamic_cast for type checking and forwarding the cast argument to its proper method. I have two questions:
1. Would this be considered good practice? Say if I have a hundred of Collider pointers and casting them dynamically every game cycle?
2. Is there a better way to accomplish this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>

using namespace std;

class Collider {
public:
    virtual ~Collider() { }
    virtual void collideWith(Collider* other) = 0;
};

class BoxCollider;

class CircleCollider : public Collider {
    virtual void collideWith(Collider* other);
    virtual void collideWith(BoxCollider* other);
    virtual void collideWith(CircleCollider* other);
};

class BoxCollider : public Collider {
public:
    virtual void collideWith(Collider* other) {
        BoxCollider *b = dynamic_cast<BoxCollider*>(other);
        if (b != nullptr) {
            collideWith(b);
            return;
        }
        CircleCollider *c = dynamic_cast<CircleCollider*>(other);
        if (c != nullptr) {
            collideWith(c);
            return;
        }
    }
    virtual void collideWith(BoxCollider* other) {
        cout << "Collide Box with Box\n";
    }
    virtual void collideWith(CircleCollider* other) {
        cout << "Collide Box with circle\n";
    }
};


void CircleCollider::collideWith(BoxCollider* other) {
    cout << "Collide circle with Box\n";
}
void CircleCollider::collideWith(CircleCollider* other) {
    cout << "Collide circle with circle\n";
}

void CircleCollider::collideWith(Collider* other) {
    BoxCollider *b = dynamic_cast<BoxCollider*>(other);
    if (b != nullptr) {
        collideWith(b);
        return;
    }
    CircleCollider *c = dynamic_cast<CircleCollider*>(other);
    if (c != nullptr) {
        collideWith(c);
        return;
    }
}


int main(int argc, const char * argv[]) {

    Collider *box = new BoxCollider();
    Collider *cir = new CircleCollider();
    
    box->collideWith(cir);
    cir->collideWith(box);
    
    
    delete box;
    delete cir;
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.