Pergunta

I'm about to desperate! I need to call a non-virtual member function from a pointer to my base class:

class A {  };

class B : public A { public: void evilFunction() { std::cout << "Yay!"; } };

int main(void) {
    A *pointer = new B();

    // Now do something like this: 
    // pointer->evilFunction();

    return 0;
}

I know I can do this with dynamic_cast - but I'm not allowed to! I really have no idea what else I can do. In theory, since I have the pointer, I'm pretty sure I can do some magic with pointer arithmetics to get the memory position of the function and then call it, but I don't know how to do this or at least how to start.

Any one who can give me a hint? That's all I need. Or I'm gonna use my epic beginner skills to write code to delete g++ in retaliation for the pain C++ is causing to me! You can't let that happen, right?!

Foi útil?

Solução

When you know that the pointer really points to a B, then just use a static_cast.


int main()
{
    A *pointer = new B();

    // Now do something like this: 
    // pointer->evilFunction();
    static_cast<B*>( pointer )->evilFunction();
}

Outras dicas

The main question here, is why are you not allowed to use dynamic_cast.

If this is because you do not use RTTI, and you can still use static_cast - this may be your answer.

However, if this is because of code-standard or alike, I would imagine that static_cast, or any "magic" would also be prohibited, and therefore, you will have to think of another solution (for example, making this method virtual, adding "manual typeid" to the base-class, and dispatching accordingly(hate this...), etc.)

If the reason for not wanting to use virtual functions is to avoid RTTI, you could achieve static polymorphism using the CRTP idiom.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top