0

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!

anon
  • 41,035
  • 53
  • 197
  • 293
  • 1
    This answer to another question has a good list of what you can and cannot do with an incomplete type: http://stackoverflow.com/questions/553682/when-to-use-forward-declaration/553869#553869 – James McNellis Jan 31 '10 at 06:13

2 Answers2

5

This doesn't work and it isn't doing quite what you think it is. Your use of the c-style cast:

(Foo*) bar

is incorrect in this case. What you are trying to do is upcast the Bar* to a Foo* (i.e., perform a static_cast from a pointer to a dervied class to a pointer to a base class).

Since the definition of Bar is not available at this point, however, the compiler does not know that Foo is a base class of Bar. Thus, the static_cast fails and the compiler falls back and uses a reinterpret_cast, which is not at all the same thing.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
0

Hmm. My guess is that since the cast is "evaluated" during linking, which is after the class has been compiled. But that's just a guess.

Narfanator
  • 5,595
  • 3
  • 39
  • 71