I define 2 classes
class BaseA { public: virtual void methodA() = 0; }; class BaseB { public: virtual void methodB(int val) = 0; }; Child inherits 2 Base Class
class Child : public BaseA, public BaseB { public: void methodA() override { printf("Child A\n"); } void methodB(int val) override { printf("Child B %d\n", val); } }; Then I write following code.
void callBaseB(void *p) { BaseB *b = (BaseB *) p; b->methodB(0); } int main() { auto child = new Child; callBaseB(child); return 0; } console print Child A
Why this happened? Why not call method B?
(This is what happend when a Java engineer try to write C++ code)
void *to aBaseB *like that. You have completely flummoxed the compiler.void*here instead of usingBaseB*?void*is one of those C++ constructs that should only be used if there is no other way to solve the problem and only if being very careful not to make a mistake.void*back to original type and nothing else. Related/duplicate: C++ typecast: cast a pointer from void pointer to class pointer, Casting to void* and Back to Original_Data_Type*