In the followint code, how does the pointer conversion & multi-inheritance play together?
class Foo {
public:
virtual void someFunc();
};
class Bar;
void someWork(Bar *bar) {
((Foo*) bar)->someFunc();
}
class Bar: public Zed, public Foo {
...
virtual void someFunc() { ... do something else ... }
}
Bar bar;
int main() {
someWork(&bar);
}
My understanding is kinda shaky.
On one hand, someWork knows nothing about Bar, so this shouldn’t work; but on the other hand, I have forward declared Bar.
Thanks!
This doesn’t work and it isn’t doing quite what you think it is. Your use of the c-style cast:
is incorrect in this case. What you are trying to do is upcast the
Bar*to aFoo*(i.e., perform astatic_castfrom a pointer to a dervied class to a pointer to a base class).Since the definition of
Baris not available at this point, however, the compiler does not know thatFoois a base class ofBar. Thus, thestatic_castfails and the compiler falls back and uses areinterpret_cast, which is not at all the same thing.