Question

I got a function that have two base class pointers and depending on the subclass, other functions should be called...

Like this:

    void function(A* a, A* a2){

    if (typeid(*a).name() == "B"){
        if(typeid(*a2).name() == "C"){
            otherFunction(); 
        }
        if(typeid(*a2).name() == "D"){
            otherFunction2(); 
        }
    }
  }

However, there's a whole buncha problems:

1) I've read that typeid.name yield different result depending on the compiler and therefore I don't want to use it.

2) I've considered creating an instance of "B" and instead writing if(typeid(*a2) == typeid(instanceOfB)) but that would be a lot of work since there are plenty of constructor arguments...

3) I've also considered using dynamic_cast but some subclasses look like this:

  A <-- B <-- C

so if if I wanted to check if the argument is B with dynamic cast, it would pass even if the argument is in fact C because C inherits from B

Edit: It seems I'll have to reconsider the design but since many have stated the design is flawed I'll quickly explain what my train of thought:

There's a window. Several different objects are located inside the window and move around, a game. This function was supposed to function as a collision detection. Like this: Go through all objects on the screen, check if the have collided. Take the two collided objects as arguments and call this function. This function looks up a buncha different collisions like "if a is "an arrow" and a2 is "a bandit" then do some stuff but if a2 is "a tree" instead, do this instead!

Was it helpful?

Solution

Wouldn't it be better to have some virtual methods in A that do nothing by default and are overwritten by some of its inheriting classes?

class A {
public:
    virtual void method(A *a2) {
    }

    virtual void otherMethod() {
    }
};

class B : public A {
public:
    virtual void method(A *a2) {
        a2->otherMethod();
    }
};

class C : public B {
public:
    virtual void otherMethod() {
        // do your C stuff here
    }
};

class D : public A {
public:
    virtual void otherMethod() {
        // do your D stuff here
    }
};

Would this achieve the things you are trying to do?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top